If the “list names” are always in the same order, you can do this using a list comprehension with zip
and sum
:
>>> data = [[('Lista-A', 1), ('Lista-X', 1), ('Lista-Z', 4)], [('Lista-A', 2), ('Lista-X', 0), ('Lista-Z', 1)], [('Lista-A', 5), ('Lista-X', 1), ('Lista-Z', 0)], [('Lista-A', 0), ('Lista-X', 1), ('Lista-Z', 4)]]
>>> [(col[0][0], sum(x for _, x in col)) for col in zip(*data)]
[('Lista-A', 8), ('Lista-X', 3), ('Lista-Z', 9)]
zip(*data)
is a standard way to iterate over “columns” from a list of “rows”. Assuming the columns do line up, then each column contains all the numbers to be summed for the same “list name”. The sum
function adds the numbers; the columns contain tuples where we want to sum the numbers in the second component, hence the destructuring assignment _, x
.
0
solved How can i add the numbers of tuples from different lists of a a list in Python? [closed]