Summing a list in Python - within a tuple and another list

Viewed 120

Not sure if it's a dup - will delete if so, just haven't found one for this specific scenario. I have a complex list full of tuples, which contain strings and lists.

I need to replace the deepest lists with int values, which are the sum of those lists. I've tried half a dozen loop combinations to tackle it - nothing seems to work.

[('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]

Needs to become:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

So that I can return the new list combo sorted by the values of the summed lists.

7 Answers

You can make a concise, readable comprehension with something like:

[(abbr, sum(t)) for abbr, t in l]

result:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

Using map

Ex:

lst = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]
print(list(map(lambda x: (x[0], sum(x[1])), lst)))

or list comprehension

Ex:

print([(i[0], sum(i[1])) for i in lst])

Output:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]
oldlst = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]

newlst = list([(i[0], sum(i[1])) for i in oldlst])

Check here.

Let's use list comprehensions to solve it -

myList = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]
myList_out = [(i[0],sum(i[1])) for i in myList]
myList_out
    [('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

By using collections.defaultdict.:

from collections import defaultdict
xList = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]
testDict = defaultdict(int)
for key, val in xList:           
        testDict[key] = val[0] + val[1]

print(testDict.items())

OUTPUT: out

lst = [('MED', [1, 1]),('COP', [3, 1]),('GRO', [1, 5]),('RRE', [5, 3]),('PRO', [4, 6])]

print [(text, sum(num)) for text, num in lst]

result:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]

Try this:

l1 = [('MED', [1, 1]), ('COP', [3, 1]), ('GRO', [1, 5]), ('RRE', [5, 3]), ('PRO', [4, 6])]

mod_l1 = [(abbr, sum(t)) for abbr, t in l1]

required_l1 = sorted(mod_l1, key=lambda order: order[1])

result:

[('MED', 2), ('COP', 4), ('GRO', 6), ('RRE', 8), ('PRO', 10)]
Related