Python元素方面的元组操作,如sum

时间:2009-01-31 00:51:49

标签: python tuples

有没有让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__方法的定义是这样的。那么唯一的方法就是重新定义它们吗?

13 个答案:

答案 0 :(得分:117)

import operator
tuple(map(operator.add, a, b))

答案 1 :(得分:96)

使用所有内置插件..

tuple(map(sum, zip(a, b)))

答案 2 :(得分:30)

此解决方案不需要导入:

tuple(map(lambda x, y: x + y, tuple1, tuple2))

答案 3 :(得分:19)

将前两个答案组合在一起,对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来简化子类化。

答案 4 :(得分:17)

from numpy import *

a = array( [1,2,3] )
b = array( [3,2,1] )

print a + b

给出array([4,4,4])

请参阅http://www.scipy.org/Tentative_NumPy_Tutorial

答案 5 :(得分:9)

可以使用生成器理解来代替地图。内置的地图功能并不过时,但对于大多数人来说,它比列表/生成器/字典理解的可读性差,所以我建议不要使用地图功能。

tuple(p+q for p, q in zip(a, b))

答案 6 :(得分:6)

没有返回元组的类定义的简单解决方案

import operator
tuple(map(operator.add,a,b))

答案 7 :(得分:6)

所有发电机解决方案。不确定性能(尽管itertools很快)

import itertools
tuple(x+y for x, y in itertools.izip(a,b))

答案 8 :(得分:3)

是。但是你无法重新定义内置类型。你必须将它们子类化:

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))

答案 9 :(得分:1)

更简单,没有使用地图,你可以这样做

>>> tuple(sum(i) for i in zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)

答案 10 :(得分:0)

我目前将“ tuple”类子类化以重载+,-和*。我发现它使代码更漂亮,并使编写代码更容易。

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)

答案 11 :(得分:0)

如果您已经在使用numpy,这是另一个方便的解决方案。 它紧凑,可以用任何 numpy表达式代替加法运算。

import numpy as np
tuple(np.array(a) + b)

答案 12 :(得分:-1)

如果有人需要平均一组元组:

import operator 
from functools import reduce
tuple(reduce(lambda x, y: tuple(map(operator.add, x, y)),list_of_tuples))