Python Multiply等长的元组

时间:2015-02-17 02:50:06

标签: python math tuples sequence

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

我的第一个想法是尝试(1, 2, 3) * (1, 2, 2)会产生(1, 4, 6),即单个乘法的乘积。

虽然python没有预设为序列做到这一点。哪个好,我真的不希望这样。那么,将两个系列中的每个项目与其各自的指数相乘(也可能是其他算术运算)的pythonic方法是什么?

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

5 个答案:

答案 0 :(得分:6)

最简单的方法是使用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之间的差异。

答案 1 :(得分:5)

如果您对元素乘法感兴趣,您可能会发现许多其他元素数学运算也很有用。如果是这种情况,请考虑使用numpy库。

例如:

>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> y = np.array([1, 2, 2])
>>> x * y
array([1, 4, 6])
>>> x + y
array([2, 4, 5])

答案 2 :(得分:5)

更简单的方法是:

from operator import mul

In [19]: tuple(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
Out[19]: (0, 20, 60, 120)

答案 3 :(得分:1)

使用列表推导,操作可以像

一样完成
def seqMul(left, right):
    return tuple([value*right[idx] for idx, value in enumerate(left)])

seqMul((0.6, 3.5), (4, 4))

答案 4 :(得分:1)

A = (1, 2, 3)
B = (4, 5, 6)    
AB = [a * b for a, b in zip(A, B)]

使用itertools.izip代替zip来获取更大的输入。