如何在 python 中添加两个具有不同维度的列表?

How can I add two lists having different dimensions in python?

我有一个排序的交点列表 (x, y) 如下表所示,命名为 coordinates

coordinates =[(66, 66), (132, 66), (199, 66), (266, 66), (333, 66), (399, 66), (466, 66), (533, 66)]

我还有一个数组,错误定义为 Error = [10, 32, 12, 43, 56, 23, 21,11]

假设它们的长度相同,是否可以添加 Error array 中的每个元素,使得坐标的输出应如下所示

new_coordinates = [(66+10, 66+10), (132+32, 66+32), (199+12, 66+12), ..., (533+11, 66+11)]

这是一种使用列表理解和 zip():

的方法
new_cordinates = [(x[0]+y, x[1]+y) for (x,y) in zip(coordinates, Error)]

这是单线的-

fixed_coordinates = [tuple(map(lambda x: x+e, cc)) for cc, e in zip(coordinates, Error)]

请注意,此解决方案不假定坐标的特定长度,并且同样适用于 3 维(或更多)。

这里有一个简单易懂的解决方案:

coordinates = [(66, 66), (132, 66), (199, 66), (266, 66),
               (333, 66), (399, 66), (466, 66), (533, 66)]
errors = [10, 32, 12, 43, 56, 23, 21, 11]

output = [(x + e, y + e) for (x, y), e in zip(coordinates, errors)]

print(output)

输出:

[(76, 76), (164, 98), (211, 78), (309, 109), (389, 122), (422, 89), (487, 87), (544, 77)]

什么是zip()