2012-03-03 83 views
1

我需要能夠打印出符合thresh保留條件的正確郵編碼,我可以通過它們進行篩選並對它們進行操作,但最後一步是打印哪些郵編碼在50英里的中心之一。 這裏是我的代碼經過篩選後打印字典值

import sys 
import csv 
import math 


dicts = {} 
origin =[] 
#methods to convert to radians 
def getLatRad(latitude): 
    return float(latitude) * (math.pi/180.0) 
def getLongRad(longitude): 
    return float(longitude) * (math.pi/180.0) 
#method to find which zipcodes are within thresh 
def getnearbylist(center, thresh, ziplist): 
    try: 
     f = open("zips.csv") 
     csvParser = csv.reader(f) 
     for row in csvParser: 
      zipcode= row[0].strip() 
      latitude= row[2].replace('"', '').strip() 
      longitude=row[3].replace('"', '').strip() 
      dicts[zipcode] = {'zipcode':zipcode,'latitude': latitude, 'longitude':longitude} 
     if center in dicts: 
      origin=dicts[center] 
      longRad2= getLongRad(origin['longitude']) 
      latRad2= getLatRad(origin['latitude']) 
     matched = {match: dicts[match] for match in ziplist if match in dicts} 
     for x in matched: 
      longRad1= getLongRad(matched[x]['longitude']) 
      latRad1= getLatRad(matched[x]['latitude']) 
      dlon = longRad2 - longRad1 
      dlat = latRad2 - latRad1 
      a = math.sin(dlat/2)**2 + math.cos(latRad1) * math.cos(latRad2) * math.sin(dlon/2)**2 
      c = 2 * math.asin(math.sqrt(a)) 
      m = 3960 * c 
      if m <thresh: # cant figure out how to return zipcodes instead of m value 
       print m 

    except ValueError: 
     pass 
def main(): 
    center = '12601' # Our center zipcode 
    thresh = 50 # We are looking for zipcodes within 50 miles 
    ziplist = ['12481', '10001', '12203', '10303', '12561'] # Our test list 

    nearbylist = getnearbylist(center, thresh, ziplist) # Call the function 
    print nearbylist 

if __name__ == '__main__': 
    main() 

所以不是膠印米,我想返回郵編 感謝!

+0

你想打印郵編嗎? – 2012-03-03 18:51:01

+0

符合條件的郵編 – matture 2012-03-03 19:03:01

回答

1

您需要捕獲發現在附近的拉鍊。

#capture the nearby zips in a new dict 
near_zips={} 
for x in matched: 
    longRad1= getLongRad(matched[x]['longitude']) 
    latRad1= getLatRad(matched[x]['latitude']) 
    dlon = longRad2 - longRad1 
    dlat = latRad2 - latRad1 
    a = math.sin(dlat/2)**2 + math.cos(latRad1) * math.cos(latRad2) * math.sin(dlon/2)**2 
    c = 2 * math.asin(math.sqrt(a)) 
    m = 3960 * c 
    if m <thresh: # cant figure out how to return zipcodes instead of m value 
     #add the nearby zipcodes to the dict 
     print '%f < %f' % (m,thresh) 
     print 'adding %s to near_zips' % (x,) 
     near_zips[x] = matched[x] 

#return the nearby zips 
return near_zips   
+0

這隻返回其中一個值,對於給定的郵編,它應該返回其中的2個 – matture 2012-03-03 20:00:14

+0

我的示例將返回'匹配'和'm <閾值'的任何內容。因此,無論是拉鍊不是'匹配',或'm> = thresh'。你確定你的數學和門檻正確實施嗎?我已將打印語句添加到閾值塊中以顯示通過評估的值。 – tharen 2012-03-04 06:21:40