![](/img/trans.png)
[英]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.