所以我有这个清单:
[7, 31, 31, 61, 61, 79, 29, 79, 29, 103, 37, 103, 37, 47, 47, 53, 53, 89, 5, 89, 5, 13, 13, 83, 83, 101, 53, 101, 17, 53, 11, 17, 11, 59, 17, 59, 17, 41, 41, 79, 79, 97, 3, 97, 3, 41, 19, 41, 19, 53, 53, 67, 29, 67, 29, 73, 23, 73, 23, 43, 43, 71]
我想知道是否有一种方法可以对它们进行排序,比如一对的最后一个元素是第二对的第一个元素,就像这样:
[7, 31, 31, 61, 61, 79, 79, 29, 29, 103, 103, 37 ....]
[pair1] [pair2] [pair3] [pair4] [pair5] [pair6] ...
有办法吗?你知道吗
我尝试过循环,但它只是有一个非常高的时间复杂度。你知道吗
这是我的密码:
lis=[7, 31, 31, 61, 61, 79, 29, 79, 29, 103, 37, 103, 37, 47, 47, 53, 53, 89, 5, 89, 5, 13, 13, 83, 83, 101, 53, 101, 17, 53, 11, 17, 11, 59, 17, 59, 17, 41, 41, 79, 79, 97, 3, 97, 3, 41, 19, 41, 19, 53, 53, 67, 29, 67, 29, 73, 23, 73, 23, 43, 43, 71]
for i in range(0, len(lis)-4,4):
if lis[i]==lis[i+2]:
p=lis[i]
lis[i]=lis[i+1]
lis[i+1]=p
elif lis[i]==lis[i+3]:
p = lis[i]
lis[i] = lis[i + 1]
lis[i + 1] = p
p=lis[i+2]
lis[i+2]=lis[i+3]
lis[i+3]=p
elif lis[i+1]==lis[i+3]:
p=lis[i+2]
lis[i+2]=lis[i+3]
lis[i+3]=p
print(lis)
您可以这样做,比如基于原始
list
中的index
的sort
如果你真的喜欢
pair
,那么推理:
如果第一个元素和第三个元素相等的话,听起来你想把第二个元素和第三个元素换位。你可以这样做:
这是一个相当草率的解决方案,但它应该做你的工作。你知道吗
首先,我们将数据分成两对,然后对这两对进行排序。你知道吗
相关问题 更多 >
编程相关推荐