[英]Sorting a List of Elements by the First element but if Equal sort by the second
I have constructed a list [[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
which is sorted by the first value in the list of two elements. 我已经构建了一个列表
[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
通过两个元素列表中的第一个值。 That is the part I can do. 这是我能做的部分。 What I don't know is if two elements are the same, then I want to sort it alphabetically.
我不知道的是,如果两个元素是相同的,那么我想按字母顺序对它进行排序。 The method I used to sort the first list was reversing a sorted list by the first element.
我用来对第一个列表进行排序的方法是通过第一个元素反转排序列表。 This however makes
[10, "b"]
come before [10, "a"]
but i want "a" before "b". 然而,这使
[10, "b"]
在[10, "a"]
之前出现[10, "a"]
但我想在“b”之前“a”。 Is there a way to write sort by first element in descending order and if a tie, sort alphabetically by the second element? 有没有办法按降序编写第一个元素排序,如果是平局,按第二个元素按字母顺序排序?
This works: 这有效:
>>> li=[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
>>> sorted(li,key=lambda sl: (-sl[0],sl[1]))
[[13, 'b'], [10, 'a'], [10, 'b'], [4, 'c'], [1, 'd']]
The sorted function produces a new list. 已排序的函数生成一个新列表。 You can also sort the list in place using the sort method:
您还可以使用sort方法对列表进行排序:
>>> li=[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
>>> li.sort(key=lambda sl: (-sl[0],sl[1]))
>>> li
[[13, 'b'], [10, 'a'], [10, 'b'], [4, 'c'], [1, 'd']]
You can also do a nested sort (or sort on one key, then the second key) since python uses a stable sort : 你也可以进行嵌套排序(或者对一个键进行排序,然后对第二个键进行排序 ),因为python使用了一个稳定的排序 :
>>> from operator import itemgetter
>>> li=[[13, "b"], [10, "b"], [10, "a",], [4,"c"], [1, "d"]]
>>> li.sort(key=itemgetter(1))
>>> li
[[10, 'a'], [13, 'b'], [10, 'b'], [4, 'c'], [1, 'd']]
>>> li.sort(key=itemgetter(0),reverse=True)
>>> li
[[13, 'b'], [10, 'a'], [10, 'b'], [4, 'c'], [1, 'd']]
Since there is no need for a lambda in a one element sort, I used the faster operator.itemgetter vs a lambda. 由于在一个元素排序中不需要lambda,我使用了更快的operator.itemgetter与lambda。 Whether two faster sorts are faster than one, I don't know... You can also use a lambda for this method.
两个更快的排序是否比一个更快,我不知道...你也可以使用lambda这个方法。
There is a great sort tutorial that shows many of these idioms. 有一个很好的排序教程 ,显示了许多这些习语。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.