快速筛选词典列表
问题描述:
我有大量的词典列表(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
请注意,我已经看发生器表达式,但它似乎像有存储和调用结果可能会更糟?我还没有尝试过,但我不知道如何实现它...
此外,增加信号量并不会提高时间,如果有的话。
答
你可以按类型的字典这样就可以避免在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
使用列表解析可能更快:'[X在olist如果x [ '类型'] == I X]'。 – MSeifert
这应该稍微有点帮助:不要在'lambda'组合中使用'filter',使用等价的列表理解。 '[x for x in olist if x ['type'= i]' –
@ juanpa.arrivillaga你是否在说我的代码改为 tList = [x for olist if x ['type'= i]] ? 这似乎不工作(python 3.5.1)...也没有列表(x for x ...)... – kmdewey