Python逐元素元组操作,如sum [英] Python element-wise tuple operations like sum

查看:20
本文介绍了Python逐元素元组操作,如sum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆