如果嵌套列表在第一个索引处总是只有一个字符串(如示例中所示),则可以使用
max()
在每个嵌套列表(不包括第一项)的切片上。然后,只需根据您想要的“top”结果的数量对最终输出进行切片。下面是获取具有最大值的“前”3个列表的示例。
list_of_lists = [['a',1,19,5],['b',2,4,6],['c',22,5,9],['d',12,19,20]]
# sort nested lists descending based on max value contained
sorted_list = sorted(list_of_lists, key=lambda x: max(x[1:]), reverse=True)
# slice first 3 lists (to get the "top" 3 max values)
sliced_list = sorted_list[:3]
print(sliced_list)
# OUTPUT
# [['c', 22, 5, 9], ['d', 12, 19, 20], ['a', 1, 19, 5]]
def max_lists(data, num):
results = sorted(data, key=lambda x: max(x[1:]), reverse=True)
return results[:num]
list_of_lists = [['a',1,19,5],['b',2,4,6],['c',22,5,9],['d',12,19,20]]
top_three = max_lists(list_of_lists, 3)
print(top_three)
for x in top_three:
print(f'max value: {max(x[1:])} list: {x}')
# OUTPUT
# [['c', 22, 5, 9], ['d', 12, 19, 20], ['a', 1, 19, 5]]
# max value: 22 list: ['c', 22, 5, 9]
# max value: 20 list: ['d', 12, 19, 20]
# max value: 19 list: ['a', 1, 19, 5]