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

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

问题描述

在 Python 2.7 中执行元组算术的最优雅和简洁的方法是什么(无需创建我自己的带有运算符重载的类)?

假设我有两个元组:

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 个值.

解决方案

如果你正在寻找快速,你可以使用 numpy:

<预><代码>>>>导入 numpy>>>numpy.subtract((10, 10), (4, 4))数组([6, 6])

如果你想把它保存在一个元组中:

<预><代码>>>>元组(numpy.subtract((10, 10), (4, 4)))(6, 6)

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)

My intended result is

c = a - b = (6, 6)

I currently use:

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

I also tried:

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

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.

解决方案

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天全站免登陆