Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating multiple sublists by performing an operation in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading