In itertools
there is a variant of zip
which, by combining lists of different sizes, does not discard the elements further, but uses None
for your values:
>>> teste = [[1,2,3],[4,5],[6,7,8,9]]
>>> list(izip_longest(*teste))
[(1, 4, 6), (2, 5, 7), (3, None, 8), (None, None, 9)]
Creditworthiness
Or, if specified a default value via fillvalue
, this value is used (good to assign zero and not interfere with the sum):
>>> teste = [[1,2,3],[4,5],[6,7,8,9]]
>>> list(izip_longest(*teste, fillvalue=0))
[(1, 4, 6), (2, 5, 7), (3, 0, 8), (0, 0, 9)]
Thus, you can use some list understandings to get the list of sums in a single command:
>>> x= [(y, [1, 2, 3]), (y, [4, 5]), (y, [6, 7, 8, 9])]
>>> somas = [sum(numeros) for numeros in
... izip_longest(*[segundo for primeiro,segundo in x], fillvalue=0)
... ]
>>> somas
[11, 14, 11, 9]
yes that’s right, only there’s a problem. These lists of mine inside tuples can change size, and tuples can change size. that is, the lists can be of n elements and there can be n tuples
– CSAnimor
n tuples within that list or n tuples within tuples?
– Felipe Avelar
I have a list of tuples, and within these tuples I have other lists, which we can call listings. I within the lists can have n tuples and within the lists2 can have several values, that is, it can be like this:x= [('y', [1, 2, 3, 4]), ('y', [5, 6, 7, 8]), ('y', [9, 10, 11, 12]), (13,14,15,16)]
– CSAnimor
I did not understand this last tuple, but it would not be possible to standardize the tuple to always have a value and a list in it?
– Felipe Avelar
because I was wrong, I would be: x= [('y', [1, 2, 3, 4]), ('y', [5, 6, 7, 8]), ('y', [9, 10, 11, 12]), (y,[13,14,15,16])]
– CSAnimor
@Romy, see if my issue solves your problem. (:
– Felipe Avelar