web-dev-qa-db-ja.com

Python sumのような要素ごとのタプル操作

とにかく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__メソッドは、そのように機能するように定義されています。それで、唯一の方法はそれらを再定義することでしょうか?

91
Rodrigo
import operator
Tuple(map(operator.add, a, b))
120
ironfroggy

すべてのビルトインを使用します。

Tuple(map(sum, Zip(a, b)))
103
Triptych

このソリューションはインポートを必要としません:

Tuple(map(lambda x, y: x + y, Tuple1, Tuple2))
30
Boaz Shvartzman

最初の2つの答えを組み合わせて、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)

注:サブクラス化を容易にするために、stupleの代わりにself.__class__を使用します。

19
Dana
_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 を参照してください

17
Mike

マップの代わりにジェネレーター内包表記を使用できます。組み込みのマップ関数は時代遅れではありませんが、ほとんどの人にとってはリスト/ジェネレーター/辞書の理解より読みにくいので、一般的にマップ関数を使用しないことをお勧めします。

Tuple(p+q for p, q in Zip(a, b))
10
Jaehyun Yeom

タプルを返すクラス定義のないシンプルなソリューション

import operator
Tuple(map(operator.add,a,b))
6
DemonEye

すべての発電機ソリューション。パフォーマンスについてはわかりません(itertoolsは高速ですが)

import itertools
Tuple(x+y for x, y in itertools.izip(a,b))
6
Mike

はい。ただし、組み込み型を再定義することはできません。それらをサブクラス化する必要があります:

 class MyTuple(Tuple):
 def __add __(self、other):
 if len(self)!= len(other):
 raise ValueError( "タプルの長さが一致しません ")
 MyTuple(x + y for(x、y)in Zip(self、other))
3
Doug

さらにシンプルで、マップを使用せずに、あなたはそれを行うことができます

>>> Tuple(sum(i) for i in Zip((1, 2, 3), (3, 2, 1)))
(4, 4, 4)
1
LetsPlayYahtzee

現在、「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)
0
user2012588