2017-03-16 72 views
-1

我有大量的詞典列表(200,000+),需要根據關鍵詞多次(〜11,000)過濾這些詞典。什麼是最快的方法來做到這一點?快速篩選詞典列表

我正在檢索一個dicts(olist)列表,大約225,000個字符,並且試圖根據一個鍵('type')過濾這些字典。目前,我建立了所有'類型'列表中的字典,然後迭代它,篩選每個'類型'的字典。我的問題是需要〜.3s來完成這個初始'類型'過濾器,這需要將近一個小時才能運行。我使用的線程正在讓我下降到剛剛超過10分鐘,但我想接近一半。波紋管是我的代碼的相關片段,有沒有更快的方法來做到這一點(更快的過濾器或更有效的算法)?

tLim = threading.BoundedSemaphore(500) 
... 
olist = _get_co_(h) ## this returns a list of ~225,000 dictionaries 
idlist = list(set([d['type'] for d in olist])) ## returns list of ~11,000 
for i in idlist: 
    t = Thread(target=_typeData_, args=(i,olist,cData)) 
    threads.append(t) 

def _typeData_(i,olist,cData): 
    tLim.acquire() 
    tList = list(filter(lambda x: x['type'] == i, olist)) ## takes ~0.3s 
    do stuff with tList ## takes ~0.01s 

請注意,我已經看發生器表達式,但它似乎像有存儲和調用結果可能會更糟?我還沒有嘗試過,但我不知道如何實現它...

此外,增加信號量並不會提高時間,如果有的話。

+0

使用列表解析可能更快:'[X在olist如果x [ '類型'] == I X]'。 – MSeifert

+0

這應該稍微有點幫助:不要在'lambda'組合中使用'filter',使用等價的列表理解。 '[x for x in olist if x ['type'= i]' –

+0

@ juanpa.arrivillaga你是否在說我的代碼改爲 tList = [x for olist if x ['type'= i]] ? 這似乎不工作(python 3.5.1)...也沒有列表(x for x ...)... – kmdewey

回答

1

你可以按類型的字典這樣就可以避免在filter以後:

from collections import defaultdict 
id_groups = defaultdict(list) 
for dct in olist: 
    id_groups[dct['type']].append(dct) 

現在你不需要任何過濾器,你只要遍歷這個id_groups,你會得到一個該類型的所有字典的列表:

for i, tList in id_groups.items(): 
    # the i and tList are identical to your variables in the "_typeData_" function. 
    # do something with tList