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

Generating a list based on other lists in Python

I have two lists A2 and J. I am performing an operation such that whenever J[0][i]=0, A3==[0]. I present the current and expected output.

A2 = [[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6], [1, 3, 6], [0, 2, 3, 7, 8, 10], 
      [1, 3, 4, 8, 9, 11], [5, 8, 10], [5, 6, 7, 9, 10, 11], [6, 8, 11], [5, 7, 8], [6, 8, 9]]

J=[[0, 2, 0, 6, 7, 9, 10]]
A3=[]
for i in range(0,len(J[0])): 
    if (J[0][i]==0):
        A3==[0]
    else:
        A33=A2[J[0][i]]
        A3.append(A33)
print("A3 =",A3)

The current output is

A3 = [[0, 3, 5], [1, 3, 4, 8, 9, 11], [5, 8, 10], [6, 8, 11], [5, 7, 8]]

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

A3 = [[0], [0, 3, 5], [0], [1, 3, 4, 8, 9, 11], [5, 8, 10], [6, 8, 11], [5, 7, 8]]

>Solution :

A2 = [[2, 3, 5], [3, 4, 6], [0, 3, 5], [0, 1, 2, 4, 5, 6], [1, 3, 6], [0, 2, 3, 7, 8, 10], 
      [1, 3, 4, 8, 9, 11], [5, 8, 10], [5, 6, 7, 9, 10, 11], [6, 8, 11], [5, 7, 8], [6, 8, 9]]

J=[[0, 2, 0, 6, 7, 9, 10]]
A3=[]
for i in range(0,len(J[0])): 
    if (J[0][i]==0):
        A3.append([0])  # change here
    else:
        A33=A2[J[0][i]]
        A3.append(A33)
print("A3 =",A3)

#output
A3 = [[0], [0, 3, 5], [0], [1, 3, 4, 8, 9, 11], [5, 8, 10], [6, 8, 11], [5, 7, 8]]

Instead of A3==[0] please do A3.append([0]) as A3==[0] is comparing A3 with 0 and it is doing no change to A3

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