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

  • A+

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.


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

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


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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: