質問

このように動作するように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のコードに微調整を持つ最初の2つの答えを、合成の並べ替え

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])を与えます。

を参照してください。 http://www.scipy.org/Tentative_NumPy_Tutorialする

ジェネレータの理解ではなく、地図の使用することができます。内蔵のマップ機能は時代遅れではないが、それはリスト/ジェネレータ/ dictの内包表記よりもほとんどの人にとって読みにくくだので、私は一般的にはマップ機能を使用しないことをお勧めしたい。

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))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top