简体   繁体   中英

Sort list of lists of lists based on sum of Nth element of inner lists

If I have:

a = [[['Q1', 20], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q3', 24], ['R1', 14]]]

how do I sort a so that I get:

[[['Q3', 24], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q1', 20], ['R1', 14]]]

because the sum of the second elements of the lists within those tuples are 38, 35 and 34, respectively (in the second, sorted version)? Also, there has to be a better way to have this all organized so a suggestion regarding that would be gladly accepted!

IIUC, use the key arg + reverse=True from sorted .

>>> sorted(a, key=lambda x: sum(i[1] for i in x), reverse=True)

[[['Q3', 24], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q1', 20], ['R1', 14]]]

You can use sorted with sum :

a = [[['Q1', 20], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q3', 24], ['R1', 14]]]
new_a = sorted(a, key=lambda x:sum(c for _, c in x), reverse=True)

Output:

[[['Q3', 24], ['R1', 14]], [['Q2', 18], ['R2', 17]], [['Q1', 20], ['R1', 14]]]

Edit: to remove listings that sum to a value greater than a specified variable, you can use a list comprehension:

final_result = [i for i in new_a if sum(c for _, c in i) < 36]

Output:

[[['Q2', 18], ['R2', 17]], [['Q1', 20], ['R1', 14]]]

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