如何在列表列表中找到具有最大值的列表

我有一份清单


list_of_lists = [['a',1,19,5]['b',2,4,6],['c',22,5,9],['d',12,19,20]]

我想获得具有最高值的前 x 个列表,因此前 3 个max(list_of_lists)将返回


[['c',22, 5,9],['d',12,19,20],['a',1,19,5]]

或者,如果我循环遍历,list_of_lists我可以根据所选列表的索引将每个列表与前 x 最大值附加到另一个列表列表中。


这是我正在使用的代码,但它有缺陷,因为我认为我需要在每个循环结束时删除选定的答案,这样它就不会出现在下一个循环中,它只查看第 4 列 (x[3])


for y in case_list:

    last_indices = [x[3] for x in case_list]

    print("max of cases is: ",max(last_indices))

目前的输出是:


max of cases is:  22

max of cases is:  22

max of cases is:  22



繁花如伊
浏览 215回答 1
1回答

拉丁的传说

如果您的嵌套列表在第一个索引处始终只有一个字符串(如您的示例中所示),那么您可以max()在每个嵌套列表的切片上使用最大值对列表列表进行排序,但不包括第一项。然后,根据您想要的“顶级”结果的数量对最终输出进行切片。以下是获取具有最大值的“前”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 containedsorted_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]]您可以将它变成一个简单的函数来获取嵌套列表的前“x”个数量(函数之后的循环纯粹是为了打印类似于您的示例的内容)。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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python