How to add two nested lists in parallel and add the result to a new list in python
I am trying to add all elements from two unequal nested lists in parallel and add the result back to another new list, I wrote a little hacky code that could add them but there is a lot wrong with At first I tried to make the pairs equal by adding 0 to the end of the list, but the code is still running into problems since the length of the first pair is 3 and the length of the second pair is 4, I also tried to use map, but I could not add an integer and NoneType.
import pdb
import itertools
x = [[2,3,3], [5,0,3]]
y = [[0,3], [2,3,3,3]]
for idx, (a, b) in enumerate(itertools.zip_longest(x, y)):
while len(a) < len(b):
x[idx].append(0)
while len(b) < len(a):
y[idx].append(0)
print(x, y)
new_list = list()
for i in zip(x, y):
for idx, j in enumerate(i):
for ind, a in enumerate(j):
val = x[idx][ind] + y[idx][ind]
new_list.append(val)
print(new_list)
the end result should be like this:
[2, 6, 3, 7, 3, 6, 3]
source to share
You can just use itertools.zip_longest
and fill with help 0
like this
>>> from itertools import zip_longest as zip
>>> x = [[2, 3, 3], [5, 0, 3]]
>>> y = [[0, 3], [2, 3, 3, 3]]
>>> [k + l for i, j in zip(x, y, fillvalue=[0]) for k, l in zip(i, j, fillvalue=0)]
[2, 6, 3, 7, 3, 6, 3]
This could work even if x
they y
have an unequal number of elements,
>>> from itertools import zip_longest as zip
>>> x = [[2, 3, 3], [5, 0, 3], [1]]
>>> y = [[0, 3], [2, 3, 3, 3]]
>>> [k + l for i, j in zip(x, y, fillvalue=[0]) for k, l in zip(i, j, fillvalue=0)]
[2, 6, 3, 7, 3, 6, 3, 1]
Note that when we are zip
x
and y
, we are using [0]
both fillvalue
. And when we zip
i
and j
, we use 0
both fillvalue
.
So, if the number of lists in x
and is y
not equal, then [0]
fill will be used and when the number of items in i
and is j
not equal, it 0
will be used as filling.
source to share
You can use fillvalue=0
in izip_longest
to check if the checks are correct, then use the function map
to sum the archived items:
from itertools import chain,zip_longest
list(chain.from_iterable(map(sum,zip_longest(i,j,fillvalue=0)) for i,j in zip_longest(x, y)))
[2, 6, 3, 7, 3, 6, 3]
Note that if you want to iterate over the result, you don't need to use it list
(just to showcase the result).
source to share
zip_longest
very helpful here:
x = [[2,3,3], [5,0,3]]
y = [[0,3], [2,3,3,3]]
from itertools import zip_longest
res = []
for list1, list2 in zip_longest(x, y, fillvalue=[0]):
for value1, value2 in zip_longest(list1, list2, fillvalue=0):
res.append(value1 + value2)
The padding value fills the list or sublist with the specified value. In our case, a new list with [0]
for the outer loop and 0
for the inner loop.
Writing this nested list comprehension does the same thing, but it can take longer to read and understand the code. Using more lines can speed up reading and understanding. Of course, this depends a lot on the person reading the code.
source to share