Assigning certain values in a list with another list in Python

Question:

I am trying to assign values to sigma according to V at specific locations given by J. But there is mismatch with the array shape as shown in the error. I also present the expected output.

import numpy as np
J=[1,3,6,7]
arsigma=[]

V=[[], [0.9977806946852882], [0.5778527989444576], [0.5533588101522955]]
sigma=[np.array([[0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109]])]
    
for i in range(0,len(J)): 
    for j in J: 
        sigma[0][j]=V[i]
        
        arsigma.append(sigma)
        sigma=list(arsigma)

The error is

line 27, in <module>
    sigma[0][j]=V[i]

ValueError: could not broadcast input array from shape (0,) into shape (1,)

The expected output is

[np.array([[0.02109],
        [0.02109],
        [0.02109],
        [0.9977806946852882],
        [0.02109],
        [0.02109],
        [0.5778527989444576],
        [0.5533588101522955],
        [0.02109],
        [0.02109],
        [0.02109],
        [0.02109]])]
Asked By: user19862793

||

Answers:

Filter with if statement:

>>> for j, v in zip(J, V):
...      if v:
...         sigma[0][j] = v
...
>>> simga
[array([[0.02109   ],
        [0.02109   ],
        [0.02109   ],
        [0.99778069],
        [0.02109   ],
        [0.02109   ],
        [0.5778528 ],
        [0.55335881],
        [0.02109   ],
        [0.02109   ],
        [0.02109   ],
        [0.02109   ]])]
Answered By: Mechanic Pig
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.