Assigning multiple python list items at a time

Being familiar with the MATLAB programming language, I am looking for a convenient way to achieve the next destination in python.

For the list L, the given indices i and the values ​​of R

    L = [10,20,30,40,50]
    I = [2,4,5]
    R = [200, 400, 500]

I want to assign these values ​​similarly to this

    L(I) = R

which should give

    L == [10,200,30,400,500]

What is the python way to do this? A copy of the source list will also be great.

+4
source share
4 answers
for ndx, value in zip(I,R):
    L[ndx-1] = value
+2
source

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

Productivity:

[10, 200, 30, 400, 500]
+6
source

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

    [ 10 200  30 400 500]
+4

numpy:

numpy ( ). numpy:

L = [10,20,30,40,50]
I = [2,4,5]
R = [200, 400, 500]

for i in range(len(I)):
        L[I[i]-1] = R[i]

print(L)

:

[10, 200, 30, 400, 500]

. I[i]-1 I[i], Matlab 1, Python 0.

:

( ):

L = [10,20,30,40,50]
I = [1,3,4]  #fixed indexes manually
R = [200, 400, 500]

NL = [R[I.index(x)] if x in I else L[x] for x in range(len(L))]

print(NL)

:

[10, 200, 30, 400, 500]
+3
source

Source: https://habr.com/ru/post/1542232/


All Articles