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)) =)
.
you can multiplication using
lambda
Can use enumerate.
create an array of ones; multiply each list times the array; convert array to a list
Yet another answer:
-1
... requires import+1
... is very readableoutputs [10, 22, 36, 52]
The
map
function can be very useful here. Usingmap
we can apply any function to each element of an iterable.Python 3.x
Of course:
is equivalent to
So we can get our solution via:
In Python 2.x
map()
means: apply a function to each element of an iterable and construct a new list. In Python 3.x,map
construct iterators instead of lists.Instead of
my_mul
we could usemul
operatorPython 2.7
Python 3.5+
Please note that since
map()
constructs an iterator we use*
iterable unpacking operator to get a list. The unpacking approach is a bit faster then thelist
constructor:You can try multiplying each element in a loop. The short hand for doing that is