如何并行添加两个嵌套列表并将结果附加到python中的新列表 [英] How to add two nested lists in parallel and append result to a new list in python

查看:95
本文介绍了如何并行添加两个嵌套列表并将结果附加到python中的新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图并行添加两个不相等的嵌套列表的所有元素,然后将结果附加到另一个新列表中,我编写了一些hacky代码,可以添加它们,但是其中有很多问题代码,首先我尝试通过将0附加到列表末尾来使两对相等,但是由于第一对的长度为3而第二对的长度为4,代码仍然遇到问题,我也尝试使用地图,但我无法添加一个整数和一个NoneType,

I'm trying to add all the elements of two unequal nested lists in parallel and append the result back to another new list, i've written a little hacky code that could add them but there's a lot of things wrong with the code, first i tried to make the pairs equal by appending 0's to the end of the list but the code still runs into the problems since the length of the first pair is 3 and the length of the second pair is 4, i also tried using map but i couldn't add an integer and a 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)

最终结果应该是这样

[2, 6, 3, 7, 3, 6, 3]

推荐答案

您可以简单地使用 itertools.zip_longest 并用0填充,就像这样

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]

即使xy的元素数量不相等,这也将起作用

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]

请注意,当我们zip xy时,我们将[0]用作fillvalue.当我们zip ij时,我们将0用作fillvalue.

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.

因此,如果xy中的列表数不相等,则将使用[0]进行填充,并且当ij中的元素数不相等时, 0将用作填充.

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.

这篇关于如何并行添加两个嵌套列表并将结果附加到python中的新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆