有没有办法让 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))
这篇关于Python逐元素元组操作,如sum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!