Home > Net >  Combining Lists According to Index
Combining Lists According to Index

Time:05-18

With the following lists:

A=['q','r','s']
B=[0,4,0]
C=[0,0,0]

The desired output is:

D=['q',0,0,'r',4,0,'s',0,0]

My attempted solution:

D=[]
for i in B:
    D.append(A[B.index(i)])
    D.append(B[B.index(i)])
    D.append(C[B.index(i)])
print(D)

However the output here is:

D=['q', 0, 0, 'r', 4, 0, 'q', 0, 0]

You can see that 'q' repeats and I'm not sure why. The 'q' should be an 's'.

Thankyou

CodePudding user response:

This should work

# use zip function to traverse all 5 lists together
# use a nested loop to flatten the tuples created by zip
[e for x in zip(A, B, C, D, E) for e in x]
# ['asd', 1, 'ttt', 1, 0, 'qwe', 2, 'ttt', 2, 30, 'wer', 3, 'ttt', 5, 0]

CodePudding user response:

Your attempted solution fails because the list E has repetitions and you are using the index method

There are two ways you can fix your solution -

Option 1 - use a list without repetitions

for i in B:
    for j in [A, B, C, D, E]:
        G.append(j[B.index(i)])

Option 2 - don't use index

H = []
for i in range(len(E)):
    for j in [A, B, C, D, E]:
        H.append(j[i])

output

['asd', 1, 'ttt', 1, 0, 'qwe', 2, 'ttt', 2, 30, 'wer', 3, 'ttt', 5, 0]

CodePudding user response:

F=[]
for i in range(len(E)):
    F.append(A[i])
    F.append(B[i])
    F.append(C[i])
    F.append(D[i])
    F.append(E[i])
print(F)

output:

['asd', 1, 'ttt', 1, 0, 'qwe', 2, 'ttt', 2, 30, 'wer', 3, 'ttt', 5, 0]
  • Related