How to sort list of lists by highest number?

。_饼干妹妹 提交于 2021-01-28 15:19:53

问题


This is my list:

[['Alfred Jeffries', '9'], ['Peter Smalls', '10'], ['Bob Daniels', '8']]

I want to sort this numerically, highest to lowest.

Expected outcome:

[['Peter Smalls', '10'], ['Alfred Jeffries', '9'], ['Bob Daniels', '8']]

Thanks!


回答1:


Use key to specify a function of one argument that is used to extract a comparison key from each list element. The argument reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

>>> l = [['Alfred Jeffries', '9'], ['Peter Smalls', '10'], ['Bob Daniels', '8']]
>>> sorted(l, key=lambda x: int(x[1]), reverse=True)
[['Peter Smalls', '10'], ['Alfred Jeffries', '9'], ['Bob Daniels', '8']]



回答2:


This question has already got an elegant answer but i wanted to do it with itemgetter.

If the list had numbers instead of strings('9','8','10') it would be far easier

 In [7]: a=[['Alfred Jeffries', 9], ['Peter Smalls', 10], ['Bob Daniels', 8]]

In [8]: sorted(a,key=itemgetter(1), reverse=True)
Out[8]: [['Peter Smalls', 10], ['Alfred Jeffries', 9], ['Bob Daniels', 8]]

Since there are strings i need to use list comprehension.

from operator import itemgetter
a=[['Alfred Jeffries', '9'], ['Peter Smalls', '10'], ['Bob Daniels', '8']]

k=[[i[0],str(i[1])] for i in sorted([[elem[0],int(elem[1])] for elem in a],key=itemgetter(1), reverse=True)]

Output

 [['Peter Smalls', '10'], ['Alfred Jeffries', '9'], ['Bob Daniels', '8']]


来源:https://stackoverflow.com/questions/30076145/how-to-sort-list-of-lists-by-highest-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!