python - 如何并行添加两个嵌套列表并将结果附加到 python 中的新列表

标签 python list python-3.x nested-lists

我正在尝试并行添加两个不相等的嵌套列表的所有元素,并将结果追加回另一个新列表,我写了一些可以添加它们的代码,但是有很多问题代码,首先我尝试通过在列表末尾附加 0 来使对相等,但是代码仍然遇到问题,因为第一对的长度是 3,第二对的长度是 4,我也尝试使用映射,但我无法添加整数和 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,像这样

>>> 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 的元素数量不相等,这也会起作用,

>>> 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] 作为填充值。当我们 zip ij 时,我们使用 0 作为 fillvalue

因此,如果 xy 中的列表数量不相等,则 [0] 将被用于填充和当ij中的元素个数不相等时,将以0作为填充。

关于python - 如何并行添加两个嵌套列表并将结果附加到 python 中的新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30275089/

相关文章:

Python Eve MONGO_DBNAME 与 MONGO_AUTHDBNAME

list - 如何使用流和 Java 8 按属性将列表中的对象分组到其他列表中?

python - 如何检查列表 'a' 中的元素是否满足列表 'b' 中的条件?

python - send_message 函数不适用于 python discord bot

python - 关闭上/右轴刻度线

python - 获取 bool 列表的真实元素的索引作为列表/元组

python - 在 pandas 中制作具有不同大小的列表的 DataFrame

Android 房间列表或可变列表返回类型

python-3.x - 如何实现广度优先和深度优先搜索网络爬虫?

python - 如何在 Tkinter 的 Canvas 小部件中放置小部件?