Creating multiple sublists by performing an operation in Python

Question:

I have two lists A2 and Cb_new. I am performing an operating as shown below. But I want to create multiple sublists instead of one single list. I present the current and expected outputs.

A2=[[2, 3, 5], [3, 4, 6]]  

Cb_new=[[1.0, 0.0, 0.0, 0.9979508721068377, 0.0, 0.9961113206802571, 0.0, 0.0, 0.996111320680257, 0.0, 0.0]]
Cb=[]


for j in range(0,len(A2)): 
    for i in range(0,len(A2[j])):  
        Cb1=Cb_new[0][A2[j][i]]
        Cb.append(Cb1)
print(Cb)

The current output is

[0.0, 0.9979508721068377, 0.9961113206802571, 0.9979508721068377, 0.0, 0.0]

The expected output is

[[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]
Asked By: isaacmodi123

||

Answers:

You will need to use a temporary list to achieve this behavior. In your code Cb1 is always an element from Cb_new list. Instead, you should append it to a list that you reset at every iteration of outer for loop.

for j in range(0,len(A2)):
    Cb_interm = []
    for i in range(0,len(A2[j])):
        Cb1=Cb_new[0][A2[j][i]]
        Cb_interm.append(Cb1)
    Cb.append(Cb_interm)
print(Cb)

The output:

[[0.0, 0.9979508721068377, 0.9961113206802571], [0.9979508721068377, 0.0, 0.0]]
Answered By: Larisa Paliciuc
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.