问题:像sum这样的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__方法被定义为那样工作。因此,唯一的方法是重新定义它们?

Is there anyway to get tuple operations in Python to work like this:

>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)

instead of:

>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)

I know it works like that because the __add__ and __mul__ methods are defined to work like that. So the only way would be to redefine them?


回答 0

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

回答 1

使用所有内置插件

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

Using all built-ins..

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

回答 2

此解决方案不需要导入:

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

This solution doesn’t require an import:

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

回答 3

对前两个答案进行了某种组合,并对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简化子类化。

Sort of combined the first two answers, with a tweak to ironfroggy’s code so that it returns a tuple:

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)

Note: using self.__class__ instead of stuple to ease subclassing.


回答 4

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

from numpy import array

a = array( [1,2,3] )
b = array( [3,2,1] )

print a + b

gives array([4,4,4]).

See http://www.scipy.org/Tentative_NumPy_Tutorial


回答 5

可以使用生成器理解来代替map。内置的地图功能并不是过时的,但是对于大多数人来说,其可读性不如列表/生成器/字典理解,因此,我建议一般不要使用地图功能。

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

Generator comprehension could be used instead of map. Built-in map function is not obsolete but it’s less readable for most people than list/generator/dict comprehension, so I’d recommend not to use map function in general.

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

回答 6

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

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

simple solution without class definition that returns tuple

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

回答 7

所有生成器解决方案。不确定性能(不过itertools很快)

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

All generator solution. Not sure on performance (itertools is fast, though)

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

回答 8

是。但是您不能重新定义内置类型。您必须将它们子类化:

类MyTuple(tuple):
    def __add __(自己,其他):
         如果len(self)!= len(other):
             引发ValueError(“元组长度不匹配”)
         返回MyTuple(对于zip中的(x,y)为x(y,y)(self,other))

Yes. But you can’t redefine built-in types. You have to subclass them:

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))

回答 9

甚至更简单,无需使用地图,您可以做到这一点

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

even simpler and without using map, you can do that

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

回答 10

我目前将“元组”类子类化以重载+,-和*。我发现它使代码更漂亮,并使编写代码更容易。

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)

I currently subclass the “tuple” class to overload +,- and *. I find it makes the code beautiful and writing the code easier.

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)

回答 11

如果有人需要平均一个元组列表:

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

In case someone need to average a list of tuples:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。