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
I think step by step could be helpful as you mentioned you are a newbie.
>>> a = [(e[0], sum(e[1])) for e in test]
>>> a
[(['a', 'b', 'c'], 10), (['d', 'e', 'f'], 12), (['g', 'h', 'j'], 7)]
>>> b=sorted(a, key=lambda e:-e[-1])
>>> b
[(['d', 'e', 'f'], 12), (['a', 'b', 'c'], 10), (['g', 'h', 'j'], 7)]
>>> c=[e[0] for e in b]
>>> c
[['d', 'e', 'f'], ['a', 'b', 'c'], ['g', 'h', 'j']]
test = [(['a','b','c'],[3,2,5]),(['d','e','f'],[1,5,6]),(['g','h','j'],[1,2,4])]
for i in range(len(test)):
test[i]=list(test[i])
test[i][1]=sum(test[i][1]) #this iteration helps to sum up the elements
print(test)
new_list=[]
maxi=0
for i in test:
if i[1]<maxi:
new_list= new_list+[i[0]]
else:
new_list=[i[0]]+ new_list #this is to sort in descending order
maxi=i[1]
print(new_list)
output:
[[['a', 'b', 'c'], 10], [['d', 'e', 'f'], 12], [['g', 'h', 'j'], 7]]
[['d', 'e', 'f'], ['a', 'b', 'c'], ['g', 'h', 'j']]
>>>
test = [(['a','b','c'],[3,2,5]),(['d','e','f'],[1,5,6]),(['g','h','j'],[1,2,4])]
def sum_of_list(l):
# Returns sum of the list
total = 0
for val in l:
total = total + val
return total
def Sort_Tuple(tup):
# reverse = None (Sorts in Ascending order)
# key is set to sort using second element of
# sublist lambda has been used
tup.sort(key = lambda x: x[1], reverse = True)
return tup
result1 = []
for t in test:
result1.append((t[0],sum_of_list(t[1])))
result1 = Sort_Tuple(res1)
result = [ _[0] for _ in result1]
print(result)
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.