使用以下串列:
A=['q','r','s']
B=[0,4,0]
C=[0,0,0]
所需的輸出是:
D=['q',0,0,'r',4,0,'s',0,0]
我嘗試的解決方案:
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)
但是這里的輸出是:
D=['q', 0, 0, 'r', 4, 0, 'q', 0, 0]
你可以看到'q'重復,我不知道為什么。“q”應該是一個“s”。
謝謝
uj5u.com熱心網友回復:
這應該作業
# 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]
uj5u.com熱心網友回復:
您嘗試的解決方案失敗,因為串列E有重復并且您正在使用該index方法
有兩種方法可以修復您的解決方案 -
選項 1 - 使用不重復的串列
for i in B:
for j in [A, B, C, D, E]:
G.append(j[B.index(i)])
選項 2 - 不要使用索引
H = []
for i in range(len(E)):
for j in [A, B, C, D, E]:
H.append(j[i])
輸出
['asd', 1, 'ttt', 1, 0, 'qwe', 2, 'ttt', 2, 30, 'wer', 3, 'ttt', 5, 0]
uj5u.com熱心網友回復:
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)
輸出:
['asd', 1, 'ttt', 1, 0, 'qwe', 2, 'ttt', 2, 30, 'wer', 3, 'ttt', 5, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477845.html
上一篇:回圈組合出錯-函式(多個資料幀)
