Python将等长的元组相乘 [英] Python Multiply tuples of equal length
问题描述
我希望能找到一种优雅或有效的方法来乘以整数序列(或浮点数).
I was hoping for an elegant or effective way to multiply sequences of integers (or floats).
我的第一个想法是尝试(1、2、3)*(1、2、2)
会产生(1、4、6)
,即产品各个乘法的数量.
My first thought was to try (1, 2, 3) * (1, 2, 2)
would result (1, 4, 6)
, the products of the individual multiplications.
尽管python尚未预先设置为执行序列操作.很好,我真的不希望如此.那么,将两个系列中的每个项目与各自的索引相乘并相乘的Python方法是什么?
Though python isn't preset to do that for sequences. Which is fine, I wouldn't really expect it to. So what's the pythonic way to multiply (or possibly other arithmetic operations as well) each item in two series with and to their respective indices?
第二个示例(0.6,3.5)*(4,4)
= (2.4,14)
推荐答案
The simplest way is to use zip
function, with a generator expression, like this
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
,就像这样
In Python 2.x, zip
returns a list of tuples. If you want to avoid creating the temporary list, you can use itertools.izip
, like this
>>> 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)
您可以在 itertools.izip
之间的区别.>这个问题.
You can read more about the differences between zip
and itertools.izip
in this question.
这篇关于Python将等长的元组相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!