2009-01-31 76 views
73

反正是有得到的元组操作在Python这样的工作:的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__方法被定义为像那样工作。所以唯一的办法是重新定义它们?

回答

102
import operator 
tuple(map(operator.add, a, b)) 
+4

我会说这是最pythonic解决方案。 – 2009-01-31 01:34:11

+2

除map()是半弃的。有关Guido的文章,请参阅http://www.artima.com/weblogs/viewpost.jsp?thread=98196,其中提到地图作为列表理解如何写得更好。 – 2012-02-13 21:07:13

+0

如果a&b不包含相同数量的元素,或者不是“可加”(例如`map(operator.add,(1,2),(“3”,“4” ))` – 2012-02-13 21:09:34

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)) 
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缓解子类。

78

使用所有的内置插件..

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

无类定义简单的解决方案,返回元组

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

所有发电机解决方案。不知道对性能(itertools快,虽然)

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

这个解决方案并不需要进口:

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

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

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

更简单和无需使用的地图,你可以做到这一点

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

万一有人需要平均元组的列表:

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