我只是想知道是否有一种特殊的pythonic方式添加两个元组元素?
到目前为止(a和b是元组),我有
map(sum, zip(a, b))
Run Code Online (Sandbox Code Playgroud)
我的预期输出是:
(a[0] + b[0], a[1] + b[1], ...)
Run Code Online (Sandbox Code Playgroud)
并且可能的重量是给予0.5重量和b 0.5重量,或者等等.(我试图加权平均值).
哪个工作正常,但说我想增加一个权重,我不太确定我会怎么做.
谢谢
Chr*_*ett 18
压缩它们,然后对每个元组求和.
[sum(x) for x in zip(a,b)]
Run Code Online (Sandbox Code Playgroud)
编辑:这是一个更好的,虽然更复杂的版本,允许加权.
from itertools import starmap, islice, izip
a = [1, 2, 3]
b = [3, 4, 5]
w = [0.5, 1.5] # weights => a*0.5 + b*1.5
products = [m for m in starmap(lambda i,j:i*j, [y for x in zip(a,b) for y in zip(x,w)])]
sums = [sum(x) for x in izip(*[islice(products, i, None, 2) for i in range(2)])]
print sums # should be [5.0, 7.0, 9.0]
Run Code Online (Sandbox Code Playgroud)
如果你不介意依赖,你可以使用 numpy 对数组进行元素操作
>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([3, 4, 5])
>>> a + b
array([4, 6, 8])
Run Code Online (Sandbox Code Playgroud)
>>> a = (1, 2, 3)
>>> b = (4, 5, 6)
>>> def averageWeightedSum(args):
return sum(args) / len(args)
>>> tuple(map(averageWeightedSum, zip(a, b)))
(2.5, 3.5, 4.5)
Run Code Online (Sandbox Code Playgroud)
另一种选择是先应用权重。这也将使您具有不同的权重:
>>> from operator import mul
>>> weights = (0.3, 0.7)
>>> tuple(sum(map(mul, x, weights)) for x in zip(a, b))
(3.0999999999999996, 4.1, 5.1)
>>> weights = (0.5, 0.5)
>>> tuple(sum(map(mul, x, weights)) for x in zip(a, b))
(2.5, 3.5, 4.5)
Run Code Online (Sandbox Code Playgroud)