通过内部列表编号对python中的嵌套列表进行排序 [英] Sort a nested list in python by inner list number

查看:113
本文介绍了通过内部列表编号对python中的嵌套列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个这样的嵌套列表,

say I have a nested list such as this,

[
    ['a', [2, 3, 7]], 
    ['j', [63, 4, 0]], 
    ['c', [1, 155, 10]], 
    ['z', [0, 77, 7]], 
    ['f', [100, 42, 9]]
]

如何按照最里面的列表中选择的最大数字对它进行排序?例如,如果我们要按每个元素列表中从最大到最小的第一个整数对它进行排序,结果将是

How do sort this by the chosen largest number in the innermost list? For instance, if we wanted to sort it by the first integer in each element's list from largest to smallest, the result would be

[
    ['f', [100, 42, 9]], 
    ['j', [63, 4, 0]], 
    ['a', [2, 3, 7]], 
    ['c', [1, 155, 10]], 
    ['z', [0, 77, 7]]
]

推荐答案

您需要使用key提取要进行排序的值;在这里是element[1][0]:

You need to use a key that extracts the value by which to sort; here that is element[1][0]:

sorted(inputlist, key=lambda e: e[1][0], reverse=True)

reverse=True可以从最大到最小排序.

The reverse=True is there to sort from largest to smallest.

这篇关于通过内部列表编号对python中的嵌套列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆