我有一个这样的清单,
M=[[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19,
1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70,
92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16,
94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77,
73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27,
29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62,
98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]
我希望按照"零"上的最大数字对其进行排序。列表中每个元素的位置,例如
M=[[75], [95, 64], [82, 47, 17], [87, 35, 18, 10].....]
我试图使用一把钥匙,但它不能很好地工作,我也不知道为什么它不能正常工作......这就是关键
def Len(elem):
for i in range(16):
y=len(K[i])
return elem[y-1]
y=sorted(K,key=Len)
print(y)
也许我只是不理解关键功能。 感谢
答案 0 :(得分:5)
只需使用sorted
(或list.sort
)而不使用key
。他们已经按字典顺序排序了。
>>> sorted(M, reverse=True)
[[99, 65, 4, 28, 6, 16, 70, 92], [95, 64], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [88, 2, 77, 73, 7, 63, 67], [75], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [41, 41, 26, 56, 83, 40, 80, 70, 33], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [18, 35, 87, 10], [17, 47, 82], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]
编辑:
单独对列表进行排序:
>>> [sorted(sublist, reverse=True) for sublist in M]
[[75], [95, 64], [82, 47, 17], [87, 35, 18, 10], [82, 65, 47, 20, 4], [75, 34, 23, 19, 3, 1], [88, 77, 73, 67, 63, 7, 2], [99, 92, 70, 65, 28, 16, 6, 4], [83, 80, 70, 56, 41, 41, 40, 33, 26], [94, 72, 48, 47, 41, 37, 33, 32, 29, 16], [97, 91, 71, 65, 53, 52, 51, 44, 43, 25, 14], [78, 77, 73, 70, 68, 57, 39, 33, 28, 17, 17, 11], [91, 91, 71, 58, 52, 50, 48, 43, 38, 29, 27, 17, 14], [89, 87, 73, 69, 68, 67, 66, 63, 53, 40, 31, 30, 16, 4], [98, 98, 93, 73, 70, 62, 60, 53, 38, 27, 23, 23, 9, 4, 4]]
答案 1 :(得分:1)
尝试将operator itemgetter函数作为键。
像这样:
from operator import itemgetter
sorted(K,key=itemgetter(0))
答案 2 :(得分:0)
尝试使用每个元素的索引:
for i in M:
M[M.index(i)]=sorted(i,reverse=True)