How to sort a list of lists by a specific index of

2019-01-01 14:37发布

I have a list of lists. For example,

[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]

If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python?

8条回答
姐姐魅力值爆表
2楼-- · 2019-01-01 14:52

More easy to understand (What is Lambda actually doing):

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)
查看更多
春风洒进眼中
3楼-- · 2019-01-01 14:56

I think lambda function can solve your problem.

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']]
查看更多
不流泪的眼
4楼-- · 2019-01-01 14:56
array.sort(key = lambda x:x[1])

You can easily sort using this snippet, where 1 is the index of the element.

查看更多
宁负流年不负卿
5楼-- · 2019-01-01 15:05

This is a job for itemgetter

>>> 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']]

It is also possible to use a lambda function here, however the lambda function is slower in this simple case

查看更多
君临天下
6楼-- · 2019-01-01 15:11

in place

>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> l.sort(key=lambda x: x[2])

not in place using sorted:

>>> sorted(l, key=lambda x: x[2])
查看更多
牵手、夕阳
7楼-- · 2019-01-01 15:14

multiple criteria can also be implemented through lambda function

sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))
查看更多
登录 后发表回答