2016-03-27 64 views
2

我目前有兩個列表:寫CSV多變量

lat = [34.78, 34.82, 34.86, 34.92] 
lon = [-86.02, -86.06, -86.10, -86.14] 

我想寫的是將它們作爲經/緯度csv文件:

34.78, -86.02 
34.82, -86.06 
34.86, -86.10 
34.92, -86.14 

我試着使用:

with open('lat_lon', 'w') as csvfile: 
    writer=csv.writer(csvfile, delimiter=',') 
    writer.writerow(lat) 
    writer.writerow(lon) 

但是,這給了我所有在一行中的緯度值和在單獨的行中的lon值。任何想法如何糾正?謝謝!

回答

2

你只需要zip和使用writerows代替writerow的:

with open('lat_lon', 'w') as csvfile: 
    writer=csv.writer(csvfile, delimiter=',') 
    writer.writerows(zip(lat, lon)) 
2

就快,這樣做:

with open('lat_lon', 'w') as csvfile: 
    writer = csv.writer(csvfile, delimiter=',') 
    for la, lo in zip(lat, lon): 
     writer.writerow([la, lo]) 

或者更簡潔(如上指出):

with open('lat_lon', 'w') as csvfile: 
    writer = csv.writer(csvfile, delimiter=',') 
    writer.writerows(zip(lat, lon)) 
+0

你在我輸入的時候抓住了我的答案! – user530873

+0

對不起,發生這種事! :) – DevShark

1
import pandas as pd 
lat = [34.78, 34.82, 34.86, 34.92] 
lon = [-86.02, -86.06, -86.10, -86.14] 

output = pd.DataFrame(lat, columns=['lat']) 
output['lon'] = lon 
output.to_csv('lat_lon', index=False) 
0

關鍵是拉鍊(經緯度)。你可以像這樣使上面的答案更加緊湊。

import csv 
with open('lat_lon', 'w') as csvfile: 
    csv.writer(csvfile).writerows(zip(lat, lon))