我一直致力于使用国家邮政编码列表命名N个邮政编码列表的无sql解决方案。到目前为止,我有以下形式的新南威尔士州参考字典:
{'Belowra':2545,'Yambulla':2550,'Bingie':2537,... [n = 4700]
我 函数使用它来查找邮政编码的名称:
def look_up_sub(pc, settings):
output=[]
for suburb, postcode in postcode_dict.items():
if postcode == pc and settings=='random':#select match at random
print(suburb) #remove later
output.append(suburb)
break #stop searching for matches
elif postcode == pc and settings=='all': #print all possible names for postcode
print(suburb) #remove later
return output
N=[2000,2020,2120,2019]
for i in N:
look_up_sub(i, 'random')
>>>Millers Point
>>>Mascot
>>>Westleigh
>>>Banksmeadow
虽然可以用于小型列表,但是当N足够大时,这种低效的方法非常慢。我一直在考虑如何使用numpy数组来大大提高速度,并且正在寻找更快的方法来解决这个问题。
答案 0 :(得分:0)
您的数据结构是向后的,它应该从postcode:suburb
开始,然后当您通过它时,您会获得一个郊区列表,然后从该列表中随机选择或在列表中打印所有这些。
这是你应该做的,首先,扭转你的命令:
import defaultdict
post_to_burb = defaultdict(list)
for suburb, postcode in postcode_dict.items():
post_to_burb[postcode].append(suburb)
现在,您的函数应该执行以下操作:
import random
def look_up_sub(pc, settings):
output = []
if settings == "random":
output.append(random.choice(post_to_burb[pc]))
elif settings == 'all':
output.extend(post_to_burb[pc])
return output
在这里使用numpy会不合适,特别是因为你正在使用字符串。您可能会在运行时获得一些边际的不确定性,但您的整体算法仍然是线性时间。一旦你设置了post_to_burb
字典,现在就是恒定的时间。
答案 1 :(得分:0)
从邮政编码到郊区建立一个字典:
from collections import defaultdict
code_to_urbs = defaultdict(list)
for suburb, postcode in postcode_dict.items():
code_to_urbs[postcode].append(suburb)
完成后,您只需编写code_to_urbs[postal_code]
。