How to perform element-wise multiplication of two

2019-01-04 07:07发布

I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.

This is how I would do it in Matlab.

a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]

A list comprehension would give 16 list entries, for every combination x * y of x from a and y from b. Unsure of how to map this.

If anyone is interested why, I have a dataset, and want to multiply it by Numpy.linspace(1.0, 0.5, num=len(dataset)) =).

14条回答
Lonely孤独者°
2楼-- · 2019-01-04 07:46

Use a list comprehension mixed with zip():.

[a*b for a,b in zip(lista,listb)]
查看更多
太酷不给撩
3楼-- · 2019-01-04 07:46

For large lists, we can do it the iter-way:

product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5])

product_iter_object.next() gives each of the element in the output list.

The output would be the length of the shorter of the two input lists.

查看更多
登录 后发表回答