我有三個列表:Python:將3個列表連接成csv文件?
name = ['rob', 'mike', 'bob'] age = ['19, '32', '88'] id = ['aaa', 'bbb', 'ccc']
有沒有辦法垂直串聯這些和如下得到CSV?
rob, 19, aaa mike, 32, bbb bob, 88, ccc
我有三個列表:Python:將3個列表連接成csv文件?
name = ['rob', 'mike', 'bob'] age = ['19, '32', '88'] id = ['aaa', 'bbb', 'ccc']
有沒有辦法垂直串聯這些和如下得到CSV?
rob, 19, aaa mike, 32, bbb bob, 88, ccc
可以利用csv模塊和zip
來做到這一點。
name = ['rob', 'mike', 'bob']
age = ['19', '32', '88']
id = ['aaa', 'bbb', 'ccc']
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
data = list(zip(name, age, id))
for row in data:
row = list(row)
spamwriter.writerow(row)
print("Program completed")
輸出:
for i,j,k in zip(name, age, id):
print ('{}, {}, {}'.format(i,j,k))
輸出:
rob, 19, aaa
mike, 32, bbb
bob, 88, ccc
你應該能夠編寫索引循環,然後只需要創建一個循環中,最後一個字符串。 –