2017-10-15 50 views
0

我有三個列表: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

+0

你應該能夠編寫索引循環,然後只需要創建一個循環中,最後一個字符串。 –

回答

0

可以利用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") 

輸出:

enter image description here

1
for i,j,k in zip(name, age, id): 
    print ('{}, {}, {}'.format(i,j,k)) 

輸出:

rob, 19, aaa 
mike, 32, bbb 
bob, 88, ccc 
1

通過使用pandas

import pandas as pd 
pd.DataFrame({'name':name,'age':age,'id':id}).to_csv('your.csv') 

enter image description here