Answers:
import operator
tuple(map(operator.add, a, b))
map(operator.add, (1,2), ("3", "4"))
tuple([item1 + item2 for item1, item2 in zip(a, b)])
等同于列表理解。
tuple(item1 + item2 for item1, item2 in zip(a, b))
。
使用所有内置插件
tuple(map(sum, zip(a, b)))
tuple(map(sum,zip(a,b))
tuple(map(sum,zip(a,b, c))
此解决方案不需要导入:
tuple(map(lambda x, y: x + y, tuple1, tuple2))
map(sum, zip(a, b))
)
对前两个答案进行了某种组合,并对Ironfroggy的代码进行了调整,以使其返回一个元组:
import operator
class stuple(tuple):
def __add__(self, other):
return self.__class__(map(operator.add, self, other))
# obviously leaving out checking lengths
>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)
注意:使用self.__class__
代替stuple
简化子类化。
from numpy import *
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
给array([4,4,4])
。
甚至更简单,无需使用地图,您可以做到这一点
>>> tuple(sum(i) for i in zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)
我目前将“元组”类子类化以重载+,-和*。我发现它使代码更漂亮,并使编写代码更容易。
class tupleN(tuple):
def __add__(self, other):
if len(self) != len(other):
return NotImplemented
else:
return tupleN(x+y for x,y in zip(self,other))
def __sub__(self, other):
if len(self) != len(other):
return NotImplemented
else:
return tupleN(x-y for x,y in zip(self,other))
def __mul__(self, other):
if len(self) != len(other):
return NotImplemented
else:
return tupleN(x*y for x,y in zip(self,other))
t1 = tupleN((1,3,3))
t2 = tupleN((1,3,4))
print(t1 + t2, t1 - t2, t1 * t2, t1 + t1 - t1 - t1)
(2, 6, 7) (0, 0, -1) (1, 9, 12) (0, 0, 0)