【发布时间】:2017-04-14 00:01:12
【问题描述】:
我一直在研究一种 no-sql 解决方案,以使用国家邮政编码列表命名 N 个邮政编码列表。到目前为止,我有新南威尔士州的参考字典,格式如下:
{'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 数组来大大加快速度,并正在寻找更快的方法来解决这个问题。
【问题讨论】:
-
你为什么要遍历你的字典来寻找匹配?这打败了整点,你还不如有一个元组列表。您的数据结构是倒退的,它应该从
postcode:suburb开始,然后当您将其传递给pc时,您会返回一个郊区列表,然后从该列表中随机选择或在列表中打印所有郊区。 -
同意!字典的美妙之处在于 O(1) 查找,迭代它真的打败了重点
-
这绝对有帮助,谢谢
postcode_dict = dict(zip(postcode,suburb)) print(postcode_dict[2000])
标签: python numpy dictionary postal-code