简体   繁体   中英

How to find the lists with max values in a list of lists (where nested lists contain strings and numbers)?

I have a list of lists

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

and I'd like to get the top x lists with the highest values so top 3 max(list_of_lists) would return

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

or if I'm looping through list_of_lists I could append each of the lists with the top x max values to another list of lists, based upon the index of the selected lists.

Here's the code I'm working with but it's flawed as I think I need to delete the selected answer at the end of each loop so it doesn't appear in the next loop and it only looks at column 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))

And the output of that is currently:

max of cases is:  22
max of cases is:  22
max of cases is:  22

This answer gives the top max list but I would like to have the flexibility to return the top x rather than just one.

This answer gives the top x max values in a single list.

If your nested lists always have only one string at the first index (as in your example), then you sort your list of lists by max value using max() on a slice of each nested list excluding the first item. Then, just slice the final output based on the number of "top" results you want. Following is an example of getting the "top" 3 lists with max values.

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]]

You could turn it into a simple function to get the top "x" number of nested lists (the loop after the function is purely to print something similar to your example).

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM