Placing elements of one list according to another list in Python

Question:

I have two lists Cb_max1 and J1. I want to place the elements of Cb_max1 according to indices in J1.

But, I am getting an error. I present the expected output.

Cb_max1 = [[0.0009847628716281426, 0.0009847628716281426, 0.0009800221856714917]]
J1=[[1, 4, 0, 0, 0, 9, 0]]

for i in range(0,len(J1[0])):
    Cb_max1=Cb_max1[0][J1[0][i]]
    print(Cb_max1)

The error is :

in <module>
    Cb_max1=Cb_max1[0][J1[0][i]]

TypeError: 'float' object is not subscriptable

The expected output is :

[[0.0009847628716281426, 0.0009847628716281426, 0, 0, 0, 0.0009800221856714917, 0]]
Asked By: bekarhunmain

||

Answers:

I’m not sure of what you are trying to do: if J1 is your index array, then 4 and 9 would result in an indexOutOfBoundError. The problem with your code is that you’re replacing Cb_max1 by a float at the first iteration of the loop, resulting into an error at the 2nd iteration.
If as I understood J1 is your index array(i.e. contains number from 0 to len(Cb_max1)-1), then the following should work:

import numpy as np
np.asarray(Cb_max1[0])[J1[0]]
Answered By: Jon99
Cb_max1 = [[0.0009847628716281426, 0.0009847628716281426, 0.0009800221856714917]]
J1=[[1, 4, 0, 0, 0, 9, 0]]

k=[x for x in J1[0] if x!=0]   #here creating a list with non zero values
print(k)
#[1, 4, 9]

d=dict(zip(k,Cb_max1[0]))
print(d)   #here creating a dictionary mapping values with Cb_max1
#{1: 0.0009847628716281426, 4: 0.0009847628716281426, 9: 0.0009800221856714917}


[[d[x] if x in d else x for x in J1[0]]] 
#[[0.0009847628716281426, 0.0009847628716281426, 0, 0, 0, 0.0009800221856714917, 0]]
Answered By: God Is One

In your for loop, the 2nd index of Cb_max1 (i.e., J1[0][i]) will returns values 4 and 9, they are out of Cb_max1 range of index.

The following code work.

Cb_max1 = [[0.0009847628716281426, 0.0009847628716281426, 0.0009800221856714917]]
J1=[[1, 4, 0, 0, 0, 9, 0]]

# Initialize result list
result = [0] * len(J1[0])

count = 0
for J1_idx, val in enumerate(J1[0]):
    if val != 0:
        result[J1_idx] = Cb_max1[0][count]
        count += 1
        
print([result])

In which, I use count as the index to access Cb_max1 list within the for loop.

Answered By: tmc
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.