簡體   English   中英

如何在列表列表中找到具有最大值的列表(嵌套列表包含字符串和數字)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM