繁体   English   中英

通过过滤后打印出字典值

[英]printing out dictionary values after filtering through it

我需要能够打印出符合脱粒保持标准的正确邮政编码,我可以对它们进行过滤并对其进行操作,但是最后一步是打印哪些邮政编码位于中心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()

因此,我不想打印m,而是要返回邮政编码,谢谢!

您需要捕获附近的拉链。

#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        

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM