72

Python 2.7 でタプル演算を実行する最もエレガントで簡潔な方法 (演算子のオーバーロードを使用して独自のクラスを作成することなく) は何ですか?

2つのタプルがあるとしましょう:

a = (10, 10)
b = (4, 4)

私の意図した結果は

c = a - b = (6, 6)

私は現在使用しています:

c = (a[0] - b[0], a[1] - b[1])

私も試しました:

c = tuple([(i - j) for i in a for j in b])

しかし、結果はでした(6, 6, 6, 6)。上記はネストされた for ループとして機能し、結果として 4 つの反復と 4 つの値が得られると思います。

4

8 に答える 8

85

高速を探している場合は、numpy を使用できます。

>>> import numpy
>>> numpy.subtract((10, 10), (4, 4))
array([6, 6])

タプルに保持したい場合:

>>> tuple(numpy.subtract((10, 10), (4, 4)))
(6, 6)
于 2013-07-02T05:52:43.153 に答える
44

1つのオプションは、

>>> from operator import sub
>>> c = tuple(map(sub, a, b))
>>> c
(6, 6)

itertools.imapの代わりとしても使えますmap

もちろん、 から 、 、 などの他の機能もoperator使用addできmulますdiv

tupleしかし、このタイプの問題はsには適していないと思うので、別のデータ構造に移行することを真剣に検討します。

于 2013-07-02T05:44:18.553 に答える
35

zipとジェネレーター式を使用します。

c = tuple(x-y for x, y in zip(a, b))

デモ:

>>> a = (10, 10)
>>> b = (4, 4)
>>> c = tuple(x-y for x, y in zip(a, b))
>>> c
(6, 6)

itertools.izipメモリ効率の高いソリューションに使用します。

ヘルプzip:

>>> print zip.__doc__
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence.
于 2013-07-02T05:41:05.243 に答える
7

ラムダはしばしば望ましくありませんが、これはインポートなしでも同様にうまく行うことができます:

tuple(map(lambda x, y: x - y, a, b))

たとえば 2 次元座標平面上の 2 点間の距離を取得する場合は、ペアの減算の絶対値を使用する必要があります。

tuple(map(lambda x ,y: abs(x - y), a, b))
于 2016-08-04T08:47:36.057 に答える
1

Kohei Kawasaki の回答への追加として、速度については、元のソリューションが実際には最速でした (少なくとも長さ 2 タプルの場合)。

>>> timeit.timeit('tuple(map(add, a, b))',number=1000000,setup='from operator import add; a=(10,11); b=(1,2)')
0.6502681339999867
>>> timeit.timeit('(a[0] - b[0], a[1] - b[1])',number=1000000,setup='from operator import add; a=(10,11); b=(1,2)')
0.19015854899998885
>>> 
于 2019-08-09T15:51:34.327 に答える
0

私の要素ごとのタプル算術ヘルパー

サポートされている操作: +、-、/、*、d

operation = 'd' は、2D 座標平面上の 2 点間の距離を計算します

def tuplengine(tuple1, tuple2, operation):
    """ 
    quick and dirty, element-wise, tuple arithmetic helper,
    created on Sun May 28 07:06:16 2017
    ...
    tuple1, tuple2: [named]tuples, both same length
    operation: '+', '-', '/', '*', 'd'
    operation 'd' returns distance between two points on a 2D coordinate plane (absolute value of the subtraction of pairs)
    """
    assert len(tuple1) == len(tuple2), "tuple sizes doesn't match, tuple1: {}, tuple2: {}".format(len(tuple1), len(tuple2))
    assert isinstance(tuple1, tuple) or tuple in type(tuple1).__bases__, "tuple1: not a [named]tuple"
    assert isinstance(tuple2, tuple) or tuple in type(tuple2).__bases__, "tuple2: not a [named]tuple"
    assert operation in list("+-/*d"), "operation has to be one of ['+','-','/','*','d']"
    return eval("tuple( a{}b for a, b in zip( tuple1, tuple2 ))".format(operation)) \
    if not operation == "d" \
      else eval("tuple( abs(a-b) for a, b in zip( tuple1, tuple2 ))")
于 2017-05-28T07:48:58.520 に答える