[英]How to Multiply the numbers within a string with another string of equal length and then add each product in Python
[英]Python Multiply tuples of equal length
我希望有一种优雅或有效的方法来乘以整数(或浮点数)序列。
我的第一个想法是尝试(1, 2, 3) * (1, 2, 2)
将导致(1, 4, 6)
,单个乘法的乘积。
虽然python没有预设为序列执行此操作。 哪个好,我真的不期望它。 那么,将两个系列中的每个项目与它们各自的指数相乘(也可能是其他算术运算)的pythonic方法是什么?
第二个例子(0.6, 3.5) * (4, 4)
= (2.4, 14)
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)
您可以在此问题中阅读有关zip
和itertools.izip
之间差异的更多信息。
如果您对元素乘法感兴趣,您可能会发现许多其他元素数学运算也很有用。 如果是这种情况,请考虑使用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])
一种更简单的方法是:
from operator import mul
In [19]: tuple(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
Out[19]: (0, 20, 60, 120)
通过列表推导,操作可以像完成一样完成
def seqMul(left, right):
return tuple([value*right[idx] for idx, value in enumerate(left)])
seqMul((0.6, 3.5), (4, 4))
A = (1, 2, 3)
B = (4, 5, 6)
AB = [a * b for a, b in zip(A, B)]
使用itertools.izip而不是zip来获取更大的输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.