Python:按“列"对列表进行排序 [英] Python: sorting a list by "column"
本文介绍了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]]
推荐答案
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屋!
查看全文