[英]Find the value of the defined key of a dict within a list, by matching the dict values
[英]python - Find all indexes for the matching value in a list of ordered dict
我有一个有序的字典列表,看起来类似于下面
[OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 1), ('b', 3)]), OrderedDict([('a', 2), ('b', 2)]), OrderedDict([('a', 3), ('b', 2)]), OrderedDict([('a', 1), ('b', 3)])]
我想将列表的索引存储在一个数组中, a
值为1
所以,我的列表将包含以下元素
[0,1,4]
我有一个传统的脚本来获取这些值,但由于我的原始列表包含超过一百万个有序字典,因此获取元素需要更长的时间。
for ele in range(len(liso)):
if(liso[ele]['a'] ==1):
giso.add(ele)
有人可以帮助我使用map
重写上述脚本或filter
以优化查询吗?
列表[i for i, x in enumerate(liso) if x['a'] == 1]
: [i for i, x in enumerate(liso) if x['a'] == 1]
过滤:
如果您使用的是Python 2: filter(lambda i: liso[i]['a'] == 1, xrange(len(liso)))
如果您使用的是Python 3: list(filter(lambda i: liso[i]['a'] == 1, range(len(liso))))
鸭子在这里工作得很好。 它在 Python 对象上构建数据库风格的索引。
pip install ducks
from ducks import Dex
objects = [OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 1), ('b', 3)]), OrderedDict([('a', 2), ('b', 2)]), OrderedDict([('a', 3), ('b', 2)]), OrderedDict([('a', 1), ('b', 3)])]
# build index on objects
dex = Dex(objects, ['a', 'b'])
# get matching objects
dex[{'a': 1}] # gets objects where a == 1
dex[{'b': 2}] # gets objects where b == 2
dex[{'a': 1, 'b': 2}] # gets objects where a == 1 and b == 2
dex[{'a': {'<': 3}}] # gets objects where a < 3
在百万项目数据集上,这些查询的运行速度将比过滤器/列表理解快 10 到 100 倍,过滤器/列表理解必须每次都扫描每个 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.