因此,根據list2
最大索引,用空值初始化您的列表。然後,使用zip
根據list1,list2
索引/值元組填充它,就像您在嘗試中那樣。
list1 = ['111', '333', '555', '777', '8888']
list2 = [1, 5, 56, 44, 2]
rows_to_write = [[""] for _ in range(max(list2))]
for i,v in zip(list2,list1):
rows_to_write[i-1][0] = v
此時rows_to_write
值得:
[['111'], ['8888'], [''], [''], ['333'], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], ['777'], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], ['555']]
然後寫在1個指令中的行(不附加)
with open('hh1.csv', 'w',newline='') as f: # python 3
csv.writer(f).writerows(rows_to_write)
這將創建一個單行 「疏」 csv文件。 (open('hh1.csv', 'wb') as f
for python 2)
你想在中間行寫什麼? –
@ Jean-FrançoisFabre它將是空的,但我需要在循環中編寫它,並且數字可能不是爲了 –