题
反正是有得到的元组操作在Python这样的工作:
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)
,而不是:
>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)
我知道它的工作原理是,由于__add__
和__mul__
方法定义这样的工作。因此,唯一的办法是重新定义它们?
解决方案
import operator
tuple(map(operator.add, a, b))
其他提示
使用所有内置插件..
tuple(map(sum, zip(a, b)))
这个解决方案不需要导入:
tuple(map(lambda x, y: x + y, tuple1, tuple2))
排序的,以便它返回一个元组组合的第一两个答案,与一个调整到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(p+q for p, q in zip(a, b))
无类定义简单的解决方案,它返回元组
import operator
tuple(map(operator.add,a,b))
所有发生器溶液。不能确定对性能(itertools是快,虽然)
import itertools
tuple(x+y for x, y in itertools.izip(a,b))
是。但你不能重新定义内建类型。你必须继承它们:
class MyTuple(tuple): def __add__(self, other): if len(self) != len(other): raise ValueError("tuple lengths don't match") return MyTuple(x + y for (x, y) in zip(self, other))
更简单和无需使用的地图,你可以做到这一点。
>>> 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)
在有人的情况下需要以平均元组的列表:
import operator
from functools import reduce
tuple(reduce(lambda x, y: tuple(map(operator.add, x, y)),list_of_tuples))
不隶属于 StackOverflow