2013-06-03 25 views
1

下面是我當前的代碼。在列表中使座標對分開的值

import csv 
def function(): 

    latitude = [] 
    longitude = [] 
    with open('data.csv', 'rU') as input: # 
      dL= list(csv.reader(input)) 
      sL = [row[4] for row in dL[1:]] 
      longitude.append(sL) 
      sL1 = [row[3] for row in dL[1:]] 
      latitude.append(sL1) 

    print latitude 
    print longitude 

    print 
    for i in range(0, len(latitude)): 
     print "Co-ordinates (" + str(latitude[i]) + "," + str(longitude[i]) + ")" 

function() 

右,所以我的輸出產生這種

[['-20.71', '-20.73', '-20.88', '-20.78', '-20.76', '-20.68', '-20.95', '-21.06', '-21.05', '-20.9']] 
[['116.77', '116.75', '116.67', '117.15', '117.16', '117.19', '117.37', '117.44', '116.26', '117.64']] 

Co-ordinates (['-20.71', '-20.73', '-20.88', '-20.78', '-20.76', '-20.68', '-20.95', '-21.06', '-21.05', '-20.9'],['116.77', '116.75', '116.67', '117.15', '117.16', '117.19', '117.37', '117.44', '116.26', '117.64']) 

這說明,我想生產名單。

我想要做什麼是產生一個輸出看起來像這樣

Co-ordinates (-20.71,116.77) 
Co-ordinates (-20.73, 116.75) 

等所有座標對。

有沒有什麼辦法讓座標輸出到我想要的輸出?

回答

2
  1. 要使用extend而不是append
  2. zip(latitude, longitude)

在第二個想法,你可以做longitude = [row[4] for row in dL[1:]]。你不需要擴展(或追加或初始化)任何東西。

更好:

with open('data.csv', 'rU') as infile: 
     dl = list(csv.reader(infile)) 
lat_long = [tuple(row[3:5]) for row in dl[1:]] 
for (lat, lng) in lat_long: 
    print "Co-ordinates ({0}, {1})".format(lat, lng) 
+0

感謝@Elazar代碼的工作非常適合我需要的東西,但是我也沒必要拉鍊經度和緯度,但感謝您的幫助。 – user2423678

0
for lat, lng in zip(latitude, longitude): 
    print "Co-ordinates (%s, %s)" % (lat, lng) 

你變換latitudelongitude到 「扁平化」,而不是列出含有一個名單列表後,該會工作。請參閱Elazar有關使用extend的提示。

+0

我沒有看到您的答案,但使用了相同的名稱,所以看起來好像我複製了它: - /。並且:我不認爲建議使用'%'運算符。 – Elazar

1

,您可以避免構建預列表和列表譜曲您使用了以下成效:

from operator import itemgetter 
from itertools import imap, islice 

with open('data.csv', 'rU') as fin: 
    dL= csv.reader(fin) 
    for lat, lon in imap(itemgetter(3, 4), islice(dL, 1, None)): 
     print 'coordinates ({}, {})'.format(lat, lon) 
+1

我喜歡在'islice()'上面使用'next(dL,None)#skip headers';這是一個更多的自我記錄。 –