执行元组算术的优雅方法 [英] Elegant way to perform tuple arithmetic

查看:79
本文介绍了执行元组算术的优雅方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.7中执行元组算术的最优雅,简洁的方法是什么(无需使用操作符重载创建我自己的类)?

What is the most elegant and concise way (without creating my own class with operator overloading) to perform tuple arithmetic in Python 2.7?

让我们说我有两个元组:

Lets say I have two tuples:

a = (10, 10)
b = (4, 4)

我的预期结果是

c = a - b = (6, 6)

我当前正在使用:

c = (a[0] - b[0], a[1] - b[1])

我也尝试过:

c = tuple([(i - j) for i in a for j in b])

,但结果为(6, 6, 6, 6).我相信以上内容可作为嵌套的for循环,在结果中产生4次迭代和4个值.

but the result was (6, 6, 6, 6). I believe the above works as a nested for loops resulting in 4 iterations and 4 values in the result.

推荐答案

如果要快速查找,可以使用numpy:

If you're looking for fast, you can use numpy:

>>> import numpy
>>> numpy.subtract((10, 10), (4, 4))
array([6, 6])

,如果您想将其保存在一个元组中:

and if you want to keep it in a tuple:

>>> tuple(numpy.subtract((10, 10), (4, 4)))
(6, 6)

这篇关于执行元组算术的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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