2

I have a set of lists:

A = [[A1,A2,A3],[A4,A5,A6]...,[A(n-2),A(n-1),A(n)]] #A has length n
B = [[B1,B2,B3],[B4,B5,B6]...,[B(n-2),B(n-1),B(n)]] #B has length n
C = [[C1,C2,C3],[C4,C5,C6]...,[C(n-2),C(n-1),C(n)]] #C has length n

and I want to sort it into the following format:

f = [(A1,A2,A3,B1,B2,B3,C1,C2,C3),(A4,A5,A6,B4,B5,B6,C4,C5,C6),...,(A(n-2),A(n-1),A(n),B(n-2),B(n-1),B(n),C(n-2),C(n-1),C(n))]

I'm pretty new to python and I cant think of a way to do this.

Any input will be greatly appreciated.

Ive started by using:

for item in range(len(A)):
   f[item][0] = A[item][0]
   f[item][1] = A[item][1]
   f[item][2] = A[item][2]

for item in range(len(B)):
   f[item][3] = B[item][0]
   f[item][4] = B[item][1]
   f[item][5] = B[item][2]

for item in range(len(C)):
   f[item][6] = C[item][0]
   f[item][7] = C[item][1]
   f[item][8] = C[item][2]   

But this just sets all items in the list f to be equal to the last item in f for some reason.

1 Answer 1

1

interleave sublists using zip, and flatten the resulting sublists with itertools.chain in a list comprehension with this nice one-liner:

import itertools

A = [["A1","A2","A3"],["A4","A5","A6"]] #A has length n
B = [["B1","B2","B3"],["B4","B5","B6"]] #B has length n
C = [["C1","C2","C3"],["C4","C5","C6"]] #C has length n

print([tuple(itertools.chain(*l)) for l in zip(A,B,C)])

result:

[('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'), ('A4', 'A5', 'A6', 'B4', 'B5', 'B6', 'C4', 'C5', 'C6')]

General case if you have a variable amount of lists, stored in a list of lists:

list_of_lists = [A,B,C]

print([tuple(itertools.chain(*l)) for l in zip(*list_of_lists)])

(use * operator to expand list items to arguments for zip)

note: works well if sublists have different lengths, as long as there are as many sublists in each list (else zip will drop the last one(s)):

A = [["A1","A2","A3"],["A4","A5","A6","A7"],["I will be discarded"]] #A has length n+1, last element will be lost
B = [["B1","B2","B3","B3bis"],["B4","B5","B6"]] #B has length n
C = [["C0","C1","C2","C3"],["C4","C5","C6"]] #C has length n

yields:

[('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'B3bis', 'C0', 'C1', 'C2', 'C3'), ('A4', 'A5', 'A6', 'A7', 'B4', 'B5', 'B6', 'C4', 'C5', 'C6')]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, could I get this to work if the lists were of different lengths? Would it be easier to make all lists equal to the length of the largest list?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.