My concern involves one of my variables which have tuples within a list as follows.
test = [(['a','b','c'],[3,2,5]),(['d','e','f'],[1,5,6]),(['g','h','j'],[1,2,4])]
I am trying to get the summation of the second tuple element of the lists for example [3,2,5]
and sort them based on that summation. so the result of that summation should be.
result1 = [(['a','b','c'],[10]),(['d','e','f'],[12]),(['g','h','j'],[7])]
then my intended final result should be sorted in descending order.
result = [['d','e','f'],['a','b','c'],['g','h','j']]
An elegant one liner:
result = [a for a, b in sorted(test, key = lambda x : sum(x[1]), reverse=True)]
sorted
returns a sorted list using the passed iterable, in this case test
key
defines the basis for sorting. Here it's a lambda expression which takes the tuple x
and returns the sum of the 2nd part of the tuple sum(x[1])
reverse
is set so that sorting is in descending order
Finally we use a list comprehension to get rid of the numeric part b
and keep only the alphabets a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With