Python乘以等长的元组

标签 python math tuples sequence

我希望有一种优雅或有效的方法来乘以整数(或 float )序列。

我的第一个想法是尝试 (1, 2, 3) * (1, 2, 2) 会得到 (1, 4, 6),乘积个体乘法。

虽然 python 没有预设为序列执行此操作。很好,我真的不希望这样。那么,将两个系列中的每个项目与其各自的索引相乘(或可能还有其他算术运算)的 Pythonic 方法是什么?

第二个例子 (0.6, 3.5) * (4, 4) = (2.4, 14)

最佳答案

最简单的方法是使用zip函数,带有 generator expression , 像这样

tuple(l * r for l, r in zip(left, right))

例如,

>>> tuple(l * r for l, r in zip((1, 2, 3), (1, 2, 3)))
(1, 4, 9)
>>> tuple(l * r for l, r in zip((0.6, 3.5), (4, 4)))
(2.4, 14.0)

在 Python 2.x 中,zip返回元组列表。如果你想避免创建临时列表,你可以使用 itertools.izip , 像这样

>>> from itertools import izip
>>> tuple(l * r for l, r in izip((1, 2, 3), (1, 2, 3)))
(1, 4, 9)
>>> tuple(l * r for l, r in izip((0.6, 3.5), (4, 4)))
(2.4, 14.0)

您可以在 this question 中阅读更多关于 zipitertools.izip 之间差异的信息.

关于Python乘以等长的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28553887/

相关文章:

python - 更改像素透明背景

.net - C# Math.Pow() 坏了

java - 在有限空间内绘制坡度线

谁能解释一下这段代码在c中排列字符串的工作原理吗?

python - 如何输入元组列表

python - 如何: setting a testsuite in python

python - 使用 win32com 打开带有公式的 Excel 文件,添加一些延迟,然后另存为 CSV

c# - 如何在一行中传递元组结果

python - 如何在 tkinter 窗口中设置鼠标位置

python - 将字典传递给以元组作为键的函数时生成的关键字错误