Python:按“列"对列表进行排序 [英] Python: sorting a list by "column"

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

问题描述

如何按列"对列表列表进行排序,即按每个列表的第i个元素对列表进行排序?

How can I sort a list-of-lists by "column", i.e. ordering the lists by the ith element of each list?

例如:

a=[['abc',5],
   ['xyz',2]]

print sortByColumn(a,0)

[['abc',5],
 ['xyz',2]]

print sortByColumn(a,1)

[['xyz',2],
 ['abc',5]]

推荐答案

您可以使用sort,其key参数等于

You could use sort with its key argument equal to a lambda function:

sorted(a, key=lambda x: x[0])
[['abc', 5], ['xyz', 2]]

sorted(a, key=lambda x: x[1])
[['xyz', 2], ['abc', 5]]

另一种方法是将key operator.itemgetter ,它将创建所需的lambda函数:

Another way would be to use key with operator.itemgetter, which creates the required lambda function:

from operator import itemgetter
sorted(a, key=itemgetter(1))
[['xyz', 2], ['abc', 5]]

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

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