Python - 如何按每个列表中的第四个元素对列表列表进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17555218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - How to sort a list of lists by the fourth element in each list?
提问by Dana Gray
I would like to sort the following list of lists by the fourth element (the integer) in each individual list.
我想按每个单独列表中的第四个元素(整数)对以下列表列表进行排序。
unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
How can I do this? Thank you!
我怎样才能做到这一点?谢谢!
回答by Taymon
unsorted_list.sort(key=lambda x: x[3])
回答by Sukrit Kalra
Use sorted()
with a key
as follows -
使用sorted()
具有key
如下-
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
所述lambda
返回每个内部列表和的第四元件sorted
函数使用排序那些列表。这假设int(elem)
列表不会失败。
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
或使用itemgetter
(正如 Ashwini 的评论所指出的,如果您有数字的字符串表示形式,则此方法将不起作用,因为对于 2 位以上的数字,它们肯定会在某处失败)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]