2009-01-31 72 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))