Being familiar with the MATLAB programming language I'm looking for a convenient way to achieve the following assignment in python.
For a list L, given indices I and values R
L = [10,20,30,40,50]
I = [2,4,5]
R = [200, 400, 500]
I want to assign these values in a similar manner to this
L(I) = R
which should yield
L == [10,200,30,400,500]
What is the python way of doing this? A copy of the original list would also be fine.
Without numpy
:
L = [10,20,30,40,50]
I = [1,3,4]
R = [200, 400, 500]
for i,j in enumerate(I):
L[j] = R[i]
print L
Yields:
[10, 200, 30, 400, 500]
If you're into using numpy
:
import numpy
L = numpy.array([10,20,30,40,50])
I = numpy.array([1,3,4]) # note the index difference (index by 0)
R = numpy.array([200,400,500])
L[I] = R
print L
yields
[ 10 200 30 400 500]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With