Python Multiply tuples of equal length

╄→尐↘猪︶ㄣ 提交于 2020-05-29 02:33:54

问题


I was hoping for an elegant or effective way to multiply sequences of integers (or floats).

My first thought was to try (1, 2, 3) * (1, 2, 2) would result (1, 4, 6), the products of the individual multiplications.

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?

A second example (0.6, 3.5) * (4, 4) = (2.4, 14)


回答1:


The simplest way is to use zip function, with a generator expression, like this

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

For example,

>>> 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)

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)

You can read more about the differences between zip and itertools.izip in this question.




回答2:


If you are interested in element-wise multiplication, you'll probably find that many other element-wise mathematical operations are also useful. If that is the case, consider using the numpy library.

For example:

>>> 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])



回答3:


A simpler way would be:

from operator import mul

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



回答4:


With list comprehensions the operation could be completed like

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

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



回答5:


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

use itertools.izip instead of zip for larger inputs.



来源:https://stackoverflow.com/questions/28553887/python-multiply-tuples-of-equal-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!