Archive

文章標籤 ‘list’

Sort list

2018年3月16日 尚無評論

How to sort a list of lists by a specific index of the inner list?
ref: How to sort a list of lists by a specific index of the inner list?

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

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

How do I sort a list of dictionaries by values of the dictionary in Python?
ref:How do I sort a list of dictionaries by values of the dictionary in Python?


[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))

newlist = sorted(l, key=itemgetter('name'), reverse=True)

Categories: Python, 程式設計 Tags: , ,