我有一个列表的列表。例如,
[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]
如果我想通过内部列表的字符串字段对外部列表进行排序,在python中如何做到这一点?
我有一个列表的列表。例如,
[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]
如果我想通过内部列表的字符串字段对外部列表进行排序,在python中如何做到这一点?
当前回答
使用一个自定义键函数,你可以很容易地排序任何列表的列表,因为你想:
L = [[0,1,'f'], [4,2,'t'], [9,4,'afsd']]
def sorter(lst):
return lst[2].casefold()
L.sort(key=sorter)
# result: [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
其他回答
array.sort(key = lambda x:x[1])
您可以很容易地使用这个代码片段进行排序,其中1是元素的索引。
我认为函数可以解决你的问题。
old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])
#Resulst of new_list will be:
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
更容易理解(Lambda实际上在做什么):
ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
def thirdItem(ls):
#return the third item of the list
return ls[2]
#Sort according to what the thirdItem function return
ls2.sort(key=thirdItem)
**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])**
如果我错了,请纠正我,但'x[2]'不是调用列表中的第三项,而不是嵌套列表中的第三项吗?应该是x[2][2]吗?
这是一个项目getter的工作
>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
在这里也可以使用lambda函数,但是在这个简单的情况下lambda函数比较慢