Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning multiple python list elements in one go

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.

like image 682
knedlsepp Avatar asked Dec 06 '22 01:12

knedlsepp


2 Answers

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]
like image 61
Dair Avatar answered Dec 08 '22 14:12

Dair


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]
like image 28
fiveclubs Avatar answered Dec 08 '22 14:12

fiveclubs