在Python中对列表列表进行排序 [英] Sorting a list of lists in Python

查看:430
本文介绍了在Python中对列表列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

c2现在是:

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

我该如何对c2进行排序,例如:

how do i sort c2 in such a way that for example:

for row in c2:

sort on row[2]

结果将是:

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

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

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

推荐答案

sort key参数指定一个参数的功能,该参数用于从每个列表元素中提取比较键.因此,我们可以创建一个简单的lambda,该lambda返回每行中要在排序中使用的最后一个元素:

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

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

一个lambda是一个简单的匿名函数.当您想创建一个像这样的简单一次性功能时.不使用lambda的等效代码为:

A lambda is 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 lambda would be:

def sort_key(row):
    return row[2]

c2.sort(key = sort_key)

如果要对更多条目进行排序,只需使key函数返回一个元组,其中包含要按重要性顺序排序的值.例如:

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

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

或:

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

这篇关于在Python中对列表列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆