Python的方式由内部列表的最后一个项目列表的列表进行排序 [英] pythonic way to sort a list of lists by the last item of the inner list
本文介绍了Python的方式由内部列表的最后一个项目列表的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样一个名单
[X,Y,1],[W,U,4],[M,N,3] ... [P,Q,5]
我所需要的外部列表由内部列表的第三次(最后一次)的元素进行排序,所期望的结果将是:
[X,Y,1],[M,N,3],[W,U,4] ... [P,Q,5]
什么是实现这一目标的最佳方式是什么?
解决方案
my_list.sort(键=拉姆达X:X [-1])
或
my_list.sort(键= operator.itemgetter(-1))
第二个选项是稍快。
I have a list like this
[[x,y,1],[w,u,4],[m,n,3] ... [p,q,5]]
I need to sort the outer list by the third (last) element of the inner list, the desired result would be:
[[x,y,1],[m,n,3],[w,u,4] ... [p,q,5]]
What's the best way to achieve this?
解决方案
my_list.sort(key=lambda x: x[-1])
or
my_list.sort(key=operator.itemgetter(-1))
The second option is slightly faster.
这篇关于Python的方式由内部列表的最后一个项目列表的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文