2014-10-19 51 views
2

我有以下Python代碼從一個TSV文件中讀取數據,並試圖用別的方法來得到兩分Python的幫助需要嵌套的循環和

代碼之間的距離TSV的數據:

import csv 

def myMethod: 

with open('data.tsv','r') as f: 
    reader = csv.reader(f,delimiter='\t') 
    for source in reader: 
     for dest in reader: 
      if source[0]!=dest[0]: 
       print("The source id is: " +source[0]) 
       print("The source long is: " +source[1]) 
       print("The source lati is: " +source[2]) 
       print("The dest id is: " +dest[0]) 
       print("The dest long is: " +dest[1]) 
       print("The dest lati is: " +dest[2]) 
       result=calculateDistance(source[1],source[2],dest[1],dest[2]) 
       print "The distance between tower" +source[0]+ "and tower " +dest[0]+ "is" +result 

我TSV文件中的數據是這樣的:

id Longitude Latitude 

1 -4.143452 5.342044 
2 -3.913602 5.341612 
3 -3.967045 5.263331 
4 -4.070007 5.451365 
5 -3.496235 6.729410 

當是看結果,外循環只運行一次。我想計算tsv文件中每個組合的距離。我想知道我可能會做錯什麼。

任何幫助將不勝感激!

謝謝!

回答

0

只是想出了這個問題,更新代碼,如下圖所示:

import csv 

def myMethod: 

with open('data.tsv','r') as f: 
    reader1 = list(csv.reader(f,delimiter='\t')) 
f.close() 

with open('data.tsv','r') as f: 
    reader = csv.reader(f,delimiter='\t') 
    for source in reader: 
     for dest in reader1: 
      if source[0]!=dest[0]: 
       print("The source id is: " +source[0]) 
       print("The source long is: " +source[1]) 
       print("The source lati is: " +source[2]) 
       print("The dest id is: " +dest[0]) 
       print("The dest long is: " +dest[1]) 
       print("The dest lati is: " +dest[2]) 
result=calculateDistance(source[1],source[2],dest[1],dest[2]) 
       print "The distance between tower" +source[0]+ "and tower " +dest[0]+ "is" +result