python 中数字降序,在列表Python中按数字降序组织然后按字母顺序升序排列

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)...]

I've tried

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.

解决方案

Return a tuple, and negate the number instead of using reverse:

list_name.sort(key=lambda x: (-x[2],) + x[:2])

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.

Demo:

>>> 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)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值