pythonlistloopsnestedlist-comprehension

Combining Lists According to Index


With the following lists:

A=['asd','qwe','wer']
B=[1,2,3]
C=['ttt', 'ttt', 'ttt']
D=[1,2,5]
E=[0,30,0]

The desired output is:

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

My attempted solution:

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

However the output here is:

['asd', 1, 'ttt', 1, 0, 'qwe', 2, 'ttt', 2, 30, 'asd', 1, 'ttt', 1, 0]

You can see that 'asd' repeats and I'm not sure why.


Solution

  • You can use zip to traverse all 5 lists together. Also using a nested loop, you can flatten the tuples created by zip.

    li = [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]