在 Python 中对列表列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3398589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:51:15  来源:igfitidea点击:

Sorting a list of lists in Python

pythonlistsorting

提问by l--''''''---------''''''''''''

c2=[]
row1=[1,22,53]
row2=[14,25,46]
row3=[7,8,9]

c2.append(row2)
c2.append(row1)
c2.append(row3)

c2is now:

c2就是现在:

[[14, 25, 46], [1, 22, 53], [7, 8, 9]]

how do i sort c2in such a way that for example:

我如何排序c2,例如:

for row in c2:

sort on row[2]

the result would be:

结果将是:

[[7,8,9],[14,25,46],[1,22,53]]

the other question is how do i first sort by row[2] and within that set by row[1]

另一个问题是我如何首先按行 [2] 排序,并在按行 [1] 设置的范围内排序

采纳答案by Dave Webb

The keyargument to sortspecifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple lambdathat returns the last element from each row to be used in the sort:

所述key参数sort指定用于提取从每个列表元素的比较关键一个参数的函数。所以我们可以创建一个简单的lambda返回每行的最后一个元素以用于排序:

c2.sort(key = lambda row: row[2])

A lambdais a simple anonymous function.It's handy when you want to create a simple single use function like this. The equivalent code not using a lambdawould be:

Alambda是一个简单的匿名函数。当您想创建这样一个简单的一次性功能时,这很方便。不使用 a 的等效代码lambda是:

def sort_key(row):
    return row[2]

c2.sort(key = sort_key)

If you want to sort on more entries, just make the keyfunction return a tuple containing the values you wish to sort on in order of importance. For example:

如果您想对更多条目进行排序,只需让key函数返回一个元组,其中包含您希望按重要性排序的值。例如:

c2.sort(key = lambda row: (row[2],row[1]))

or:

或者:

c2.sort(key = lambda row: (row[2],row[1],row[0]))

回答by mipadi

Well, your desired example seems to indicate that you want to sort by the last index in the list, which could be done with this:

好吧,您想要的示例似乎表明您想按列表中的最后一个索引进行排序,这可以通过以下方式完成:

sorted_c2 = sorted(c2, lambda l1, l2: l1[-1] - l2[-1])

回答by John La Rooy

>>> import operator
>>> c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]]
>>> c2.sort(key=itemgetter(2))
>>> c2
[[7, 8, 9], [14, 25, 46], [1, 22, 53]]