如何使用"sorted"对元组列表进行排序? [英] How do I use `sorted` to sort a list of tuples?
本文介绍了如何使用"sorted"对元组列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的元组列表
[('Raven', '18'), ('Lion', '6'), ('Unassigned', '0'), ('Cobra', '6')]
我想按元组中数字的值对它们进行排序,以实现此顺序.
I want to sort them by the value of the number in the tuple, to achieve this order.
[('Raven', '18'), ('Lion', '6'), ('Cobra', '6'), ('Unassigned', '0')]
执行此操作最好如何?我应该使用sorted()
吗?
How best is it to go about this, should I use sorted()
?
推荐答案
sorted
使用key
参数,您可以在其中指定需要进行排序的依据:
sorted
takes a key
parameter where you can specify on what basis you need the sort to happen:
lst = [('Raven', '18'), ('Lion', '6'), ('Unassigned', '0'), ('Cobra', '6')]
print(sorted(lst, key=lambda x: -int(x[1])))
# or print(sorted(lst, key=lambda x: int(x[1]), reverse=True))
# Outputs: [('Raven', '18'), ('Lion', '6'), ('Cobra', '6'), ('Unassigned', '0')]
这篇关于如何使用"sorted"对元组列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文