2017-04-14 28 views
0

我一直在研究一個無sql的解決方案,使用國家郵政編碼列表命名N個郵政編碼列表。到目前爲止,我有我的參考字典NSW的形式狀態:在Python中更快搜索 - Postcode

{ '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數組來加速這個過程,並且正在尋找更快的方法來解決這個問題。

+1

你爲什麼要迭代你的字典來尋找匹配?這使整個問題變得不那麼重要了,你可能還有一個元組列表。你的數據結構是向後的,它應該來自'postcode:suburb',然後當你通過一個'pc'時,你會得到一個郊區列表,然後從列表中隨機選擇或者在列表中打印所有列表。 –

+0

同意!字典的好處是O(1)查找,迭代它真的打敗了點 –

+0

肯定有幫助謝謝 'postcode_dict = dict(zip(postcode,suburb)) print(postcode_dict [2000])' – lm5050

回答

0

你的數據結構是向後的,它應該從postcode:suburb開始,然後當你通過一臺PC後,你會得到一個返回的郊區列表,然後從列表中隨機選擇或者在列表中打印所有列表。 這裏是你應該做的事情,第一,扭轉你的字典:

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的這裏是unweildy,特別是因爲你正在使用字符串。您可能會在運行時遇到一些邊際不確定因素,但您的整體算法仍然是線性時間。現在,一旦你設置了你的post_to_burb字典,它就是不變的時間。

+0

我做了一些相似,並在大約一秒鐘內獲得了47534個郵政編碼列表的結果,再次感謝。 – lm5050

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]