问题描述
我有一个包含三个元素的列表,格式如下:
I have a list with three elements in the following format:
[('ABC', 'DEF', 2), ('GHI', 'JKL', 6), ('MNO', 'PQR', 22), ('ABC', 'STU', 2)...]
我想按数字对最后一个元素进行排序.然后按字母顺序第一个元素.最后,如果有并列,则通过第二个元素.所以我的输出是:
I would like to sort by last element numerically. Then by first element alphabetically. Lastly by the second element if there is a tie. So my output would be:
[('MNO', 'PQR', 22), ('GHI', 'JKL', 6), ('ABC', 'DEF', 2), ('ABC', 'STU', 2)...]
我尝试过
list_name.sort(reverse=True, key=lambda x: x[2])
这仅按降序排列的最后一个元素排序.如何添加实现按字母顺序对第一和第二个元素进行排序的工具.
This only sorts by the last elements descending. How do I add the implement sorting the first and second element in that order alphabetically.
推荐答案
返回一个元组,并取反数字,而不使用reverse
:
Return a tuple, and negate the number instead of using reverse
:
list_name.sort(key=lambda x: (-x[2],) + x[:2])
这将返回(-item3, item1, item2)
,并且首先按整数item3
以降序的顺序进行排序,当绑定到数字时,按item1
进行排序(按字母顺序,升序),然后在item2
上.
This returns (-item3, item1, item2)
and sorting takes place first by the integer item3
in descending order, when tied on the number sorting is done on item1
(alphabetically, ascending order), then on item2
.
实际上,元组按字典顺序排序.
In effect, tuples are sorted in lexicographical order.
演示:
>>> list_name = [('ABC', 'DEF', 2), ('GHI', 'JKL', 6), ('MNO', 'PQR', 22), ('ABC', 'STU', 2)]
>>> list_name.sort(key=lambda x: (-x[2],) + x[:2])
>>> list_name
[('MNO', 'PQR', 22), ('GHI', 'JKL', 6), ('ABC', 'DEF', 2), ('ABC', 'STU', 2)]
这篇关于在列表Python中按数字降序组织然后按字母顺序升序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!