Tracking elements of one list with respect to the other in Python

Question:

I have lists J1 and Ci. For every zero element in J1, I want the corresponding element in Ci to be zero. For every non-zero element in J1, the corresponding element in Ci should be the same. But I am getting an error. I present the expected output.

J1 = [[0, 0, 0, 0, 0, 9, 0]]
Ci=[0.0,
 8.317333882002454e-05,
 0.0,
 8.305496451875518e-05,
 8.24723410599921e-05,
 8.257692992192182e-05,
 8.2641447034131e-05]

J1=[i for i in J1[0] if i!=0]
Ci=Ci[J1]
print(Ci)

The error is

in <module>
    Ci=Ci[J1]

TypeError: list indices must be integers or slices, not list

The expected output is

[0.0, 0.0, 0.0, 0.0, 0.0, 8.257692992192182e-05, 0.0]
Asked By: bekarhunmain

||

Answers:

The error you are getting is because you are trying to use a list as an index for another list. This is not possible as list indices must be integers or slices.

You could loop to iterate over the elements of J1 instead, and use the index of each non-zero element to access the corresponding element in Ci. If the element in J1 is zero, set the corresponding element in Ci to zero.

J1 = [[0, 0, 0, 0, 0, 9, 0]]
Ci = [0.0, 8.317333882002454e-05, 0.0, 8.305496451875518e-05, 8.24723410599921e-05, 8.257692992192182e-05, 8.2641447034131e-05]

for i, val in enumerate(J1[0]):
    if val == 0:
        Ci[i] = 0.0
    else:
        Ci[i] = Ci[val-1]

print(Ci)
Answered By: aetosti

You could do it in one comprehension using zip():

J1 = [[0, 0, 0, 0, 0, 9, 0]]
Ci=[0.0,
 8.317333882002454e-05,
 0.0,
 8.305496451875518e-05,
 8.24723410599921e-05,
 8.257692992192182e-05,
 8.2641447034131e-05]

Ci = [i if j != 0 else 0.0 for i, j in zip(Ci, J1[0])]

print(Ci)

Output:

[0.0, 0.0, 0.0, 0.0, 0.0, 8.257692992192182e-05, 0.0]

Or, using numpy:

import numpy as np

Ci = np.where(J1[0] != 0, Ci, 0.0)
Answered By: B Remmelzwaal
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.