m25*_*m25 46 python dictionary list python-2.7
我有一个字典列表和每个字典里的(比方说)"型",这可以有值的键'type1','type2'等我的目标是将这些字典筛选出到相同的词典,但只有一个的那些名单某种"类型".我想我只是在list/dictionary理解中苦苦挣扎.
所以示例列表看起来像:
exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
Run Code Online (Sandbox Code Playgroud)
我有一个关键值列表.比方说:
keyValList = ['type2','type3']
Run Code Online (Sandbox Code Playgroud)
预期结果列表的位置如下:
expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}]
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过一组for循环来做到这一点.我知道必须有一个更简单的方法.我发现这个问题有很多不同的风格,但没有一个真正适合这个问题,并回答了这个问题.我会尝试答案......但他们并没有那么令人印象深刻.可能最好让它开放结束.任何援助将不胜感激.
Bha*_*Rao 85
你可以尝试列表comp
>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用 filter
>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Run Code Online (Sandbox Code Playgroud)
kov*_*awa 40
尝试了这篇文章中的一些答案,我测试了每个答案的性能。
\n正如我最初的猜测,到目前为止,列表理解速度更快,filterandlist方法是第二,而 the是第三。pandas
\n\n定义的变量:
\n
import pandas as pd\n\nexampleSet = [{\'type\': \'type\' + str(number)} for number in range(0, 1_000_000)]\n\nkeyValList = [\'type21\', \'type950000\']\nRun Code Online (Sandbox Code Playgroud)\nlist comprehension%%timeit\nexpectedResult = [d for d in exampleSet if d[\'type\'] in keyValList]\nRun Code Online (Sandbox Code Playgroud)\n\n\n每个循环 60.7 ms \xc2\xb1 188 \xc2\xb5s(平均 7 次运行的 \xc2\xb1 标准偏差,每次 10 个循环)
\n
filter和list%%timeit\nexpectedResult = list(filter(lambda d: d[\'type\'] in keyValList, exampleSet))\nRun Code Online (Sandbox Code Playgroud)\n\n\n每个循环 94 ms \xc2\xb1 328 \xc2\xb5s(意味着 7 次运行的 \xc2\xb1 标准偏差,每次 10 个循环)
\n
pandas%%timeit\ndf = pd.DataFrame(exampleSet)\nexpectedResult = df[df[\'type\'].isin(keyValList)].to_dict(\'records\')\nRun Code Online (Sandbox Code Playgroud)\n\n\n336 ms \xc2\xb1 每个循环 1.84 ms(平均 \xc2\xb1 标准偏差 7 次运行,每次 1 次循环)
\n
顺便说一句,使用pandasa 来处理 adict并不是一个好主意,因为 apandas.DataFrame基本上会消耗更多的内存dict,并且如果您最终不打算使用数据帧,那么它的效率就会很低。
Sak*_*rma 15
使用filter,或者如果字典数exampleSet太高,则使用ifilter该itertools模块.它将返回一个迭代器,而不是立即用整个列表填充系统的内存:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
Run Code Online (Sandbox Code Playgroud)