![](/img/trans.png)
[英]How to find the min and max values of an index in nested lists with matching strings?
[英]How to find the lists with max values in a list of lists (where nested lists contain strings and numbers)?
我有一份清单清单
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 max值的列表附加到另一个列表列表中。
这是我正在使用的代码,但它有缺陷,因为我认为我需要在每个循环结束时删除所选答案,因此它不会出现在下一个循环中,它只查看第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
这个答案给出了最高的最大列表,但我希望能够灵活地返回顶部x而不是一个。
此答案给出了单个列表中的前x个值。
如果嵌套列表在第一个索引处始终只有一个字符串(如示例所示),则在每个嵌套列表的切片上使用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 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]]
您可以将其转换为一个简单的函数来获取嵌套列表的顶部“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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.