Generating a list based on other lists in Python

Question:

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 :

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

||

Answers:

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

Answered By: God Is One

Make the following changes in your code:

A3 = []
for i in J[0]:
     if i == 0:
             A3.extend([[0]])
     else:
             A3.extend([A2[i]])

Now the value of A3 is:

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

Explaination:

In your previous code A3==0 does not insert [0] to your list instead it returs a bool. Since you want to insert 0 as a single element list you can use extend function which lets you append a list with multiple elements.

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