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

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

问题描述

无论如何要让 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__ 方法被定义为这样工作.那么唯一的方法就是重新定义它们?

解决方案

import operator元组(地图(operator.add,a,b))

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?

解决方案

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

这篇关于Python 元素元元组操作,如 sum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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