简体   繁体   English

如何通过检查python子列表中的值对列表进行排序?

[英]How to sort a list by checking values in a sublist in python?

I have a list of lists in the following format: 我有以下格式的列表列表:

[['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]]

I would like to sort if in an efficient way in python using the numeric list elements, matching the first element, and when it is the same, use the second, and so on. 我想使用数字列表元素,匹配第一个元素以有效方式在python中进行排序,如果相同,则使用第二个元素,依此类推。 The result would be something like (I need reverse order this time): 结果将是这样的(这次我需要逆序):

['a',[10]]
['c',[5,10]]
['e',[5,1,-1]]
['d',[5,1,-10]
['b',[1]]

Thanks! 谢谢!

I think lists compare like you want, by default, if inverted: 我认为列表在默认情况下会按您想要的方式进行比较:

>>> data = [['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]
>>> sorted(data, reverse = True, key = lambda pair: pair[1])
[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]

You had a bracketing error in your input list, it's fixed in the code above. 您的输入列表中有一个包围错误,已在上面的代码中修复。

>>> from operator import itemgetter
>>> L=[['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]]
>>> sorted(L, key=itemgetter(1), reverse=True)
[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]
>>> 

I'd use itemgetter(1) here, which is roughly equivalent to the lambda function in the other answers. 我在这里使用itemgetter(1),它大致等效于其他答案中的lambda函数。 This effectively does the sort with the key being the sublists since they are item number 1. (item number 0 is the letters ae) 这有效地进行了排序,因为键是子列表,因为它们是项目编号1。(项目编号0是字母ae)

Use key to select the second element in the list, and reverse to change direction: 使用key选择列表中的第二个元素,然后reverse更改方向:

>>> l=[['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10], ['e',[5,1,-1]]]
>>> sorted(l, key=lambda e:e[1], reverse=True)
[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]

Lists are sorted by comparing their elements in order, just like a lexicon or regular dictionary. 列表通过按顺序比较其元素进行排序,就像词典或常规词典一样。 It's called 'lexographical comparison'. 这就是所谓的“文字比较”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM