所以,我需要通过第二个嵌套列表的第一个element
(包含01, 02, 03
等元素)对这种列表中的一些随机数据进行排序:
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']], etc]
这个随机数据稍后在defaultdict中与其他一些数据一起使用,以便将它们组合在一起并按键打印出来(键是00553, 00551
之类的数字)。
我尝试在将它放到defaultdict之前对其进行排序,但我得到的所有内容都是嵌套列表本身的值。
任何人都可以帮助我,我是新手。
答案 0 :(得分:6)
>>> lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
>>> sorted(lis, key = lambda x: int(x[1][0]))
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
答案 1 :(得分:3)
如果您不喜欢lambda
,但需要一些文档:
L = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
def by_first_of_second(sub_list):
"""First element of second entry as sort key.
Convert to int to sort by numerical value.
"""
return int(sub_list[1][0])
sorted(L, key=by_first_of_second)
结果:
[['00553', ['01', '3.4']], ['00553', ['02', '2.1']], ['00551', ['02', '5.3']]]
答案 2 :(得分:2)
lis = [['00553', ['01', '3.4']], ['00553', ['02', '2.1']],
['00551', ['02', '5.3']], ['00551', ['01', '5.3']],['00551', ['04', '5.3']]]
import operator
newlist = sorted(lis, key=operator.itemgetter(1))
结果
>>> newlist
[['00553', ['01', '3.4']], ['00551', ['01', '5.3']],
['00553', ['02', '2.1']], ['00551', ['02', '5.3']], ['00551', ['04', '5.3']]]