在Python中,我有一个嵌套列表,如下所示:
[ [[x1,y1,z1], [['0.9', 4], [0.8, 3], [0.5, 10], [0.1, 11]],
[[x2,y2,z2], [['1.0', 8], [0.8, 3], [0.2, 1], [0.1, 8]]
...]
因此每个元素都采用以下形式:
[[3-tuple], [[val1, occurrences_of_val1], [val2, occurrences_of_val2],...]]
第二个嵌套列表已经按第一个项目排序(val1> val2> val3 ...),但我还希望3元组[x,y,z]按照降序排列两个标准:
我该怎么做?可能与itemgetter有关,但在这种情况下我不确定。
答案 0 :(得分:7)
yourList.sort(key=lambda x: x[1], reverse=True)
答案 1 :(得分:3)
我测试了这个
X=[ [[4,5,6], [[3.0, 4], [0.8, 3], [0.5, 10], [0.1, 11]]],
[[2,1,3], [[2.0, 8], [0.8, 3], [0.2, 1], [0.1, 8]]]]
>>> X.sort(key=lambda x: x[1])
>>> X
[[[2, 1, 3], [[2.0, 8], [0.80000000000000004, 3], [0.20000000000000001, 1], [0.10000000000000001, 8]]], [[4, 5, 6], [[3.0, 4], [0.80000000000000004, 3], [0.5, 10], [0.10000000000000001, 11]]]]
最重要的是,X.sort(key=lambda x: x[1])
按X的第二个元素排序,即由此元素[[val1, occurrences_of_val1], [val2, occurrences_of_val2],...]
排序。隐含地,它按val1
排序,然后在occurrences_of_val1
等于...的情况下排序......