我有一套清单:
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
我希望将其分为以下格式:
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))]
我对python很陌生,我想不出办法来做到这一点。
非常感谢任何输入。
我开始使用:
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]
但是这只是将列表f中的所有项目设置为等于f中的最后一项由于某种原因。
答案 0 :(得分:1)
使用zip
交错子列表,并在列表理解中使用itertools.chain
将生成的子列表展平为这个漂亮的单行:
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)])
结果:
[('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'), ('A4', 'A5', 'A6', 'B4', 'B5', 'B6', 'C4', 'C5', 'C6')]
一般情况,如果您有可变数量的列表,存储在列表列表中:
list_of_lists = [A,B,C]
print([tuple(itertools.chain(*l)) for l in zip(*list_of_lists)])
(使用*
运算符将列表项扩展为zip
)的参数
注意:如果子列表具有不同的长度,只要每个列表中有多个子列表(否则zip
将丢弃最后一个子列表),效果很好:
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
的产率:
[('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'B3bis', 'C0', 'C1', 'C2', 'C3'), ('A4', 'A5', 'A6', 'A7', 'B4', 'B5', 'B6', 'C4', 'C5', 'C6')]