Python逐元素元组操作,如sum

2022-01-19 00:00:00 python tuples

问题描述

有没有办法让 Python 中的元组操作像这样工作:

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)

代替:

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

我知道它是这样工作的,因为 __add____mul__ 方法被定义为这样工作.那么唯一的方法就是重新定义它们?

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?


解决方案

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

相关文章