如何按给定索引处的元素对列表/元组的列表/元组进行排序? [英] How to sort a list/tuple of lists/tuples by the element at a given index?
本文介绍了如何按给定索引处的元素对列表/元组的列表/元组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在列表列表或元组列表中都有一些数据,如下所示:
I have some data either in a list of lists or a list of tuples, like this:
data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
我想按子集中的第二个元素排序.意思是,按2,5,8排序,其中2
来自(1,2,3)
,5
来自(4,5,6)
.常见的做法是什么?我应该在列表中存储元组还是列表?
And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2
is from (1,2,3)
, 5
is from (4,5,6)
. What is the common way to do this? Should I store tuples or lists in my list?
推荐答案
sorted_by_second = sorted(data, key=lambda tup: tup[1])
或:
data.sort(key=lambda tup: tup[1]) # sorts in place
这篇关于如何按给定索引处的元素对列表/元组的列表/元组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文