How to add two nested lists in parallel and append result to a new list in python

好久不见. 提交于 2019-12-05 23:05:49

You can simply use itertools.zip_longest and fill-in with 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 would would work even if x and y have 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 zip x and y, we use [0] as fillvalue. And when we zip i and j we use 0 as the fillvalue.

So, if the number of lists in x and y are not equal, then [0] will be used fill-in and when the number of elements in i and j are not equal, 0 will be used as the fill-in.

You can use fillvalue=0 in izip_longest to get ride of checking for validations then use map function for sum the zipped 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 have to use list (its just for demonstrating the result).

zip_longest is 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 fill value pads the list or sublist with the given value. In our case a new list with [0] for the outer loop and 0 for the inner loop.

Writing this a nested list comprehension does the same but may take more time to read and understand the code. Using more lines can make reading and understanding faster. Of course, this depends very much on the person reading the code.

from itertools import zip_longest

new_list = [a + b
            for listpair in zip(x, y)
            for a, b in zip_longest(*listpair, fillvalue=0)]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!