[英]What's the most efficient way to perform a multiple match lookup in a python dictionary?
我正在尋找最大程度地優化此代碼塊的運行時:
aDictionary= {"key":["value", "value2", ...
rests = \
list(map((lambda key: Resp(key=key)),
[key for key, values in
aDictionary.items() if (test1 in values or test2 in values)]))
使用python3。 願意給它盡可能多的內存。
考慮將兩個字典查找放在單獨的進程中以加快速度(這有意義嗎?)。 歡迎其他任何優化想法
對於初學者來說,當您已經在使用列表推導時,沒有理由使用map
,因此您可以刪除它以及外部list
調用:
rests = [Resp(key=key) for key, values in aDictionary.items()
if (test1 in values or test2 in values)]
第二種可能的優化可能是將每個值列表變成一個集合。 這會占用時間開始,但它會改變你的查找( in
從線性時間的使用),以固定的時間。 您可能需要為此創建一個單獨的輔助函數。 就像是:
def anyIn(checking, checkingAgainst):
checkingAgainst = set(checkingAgainst)
for val in checking:
if val in checkingAgainst:
return True
return False
然后,您可以將列表理解的末尾更改為
...if anyIn([test1, test2], values)]
但是同樣,如果您要檢查的值不止兩個,或者值中的values
列表很長,這可能才值得。
如果tests
足夠多,切換到設置操作肯定會有所回報:
tests = set([test1, test2, ...])
resps = map(Resp, (k for k, values in dic.items() if not tests.isdisjoint(values)))
# resps this is a lazy iterable, not a list, and it uses a
# generator inside, thus saving the overhead of building
# the inner list.
將dict
值轉換為集合將不會獲得任何收益,因為轉換將是O(N)
,而N
是所有values
-lists的總和,而上述不相交的操作只會迭代每個values
直到遇到遇到O(1)
的testx
為止。 O(1)
查找。
如果您不必使用lambda,則map
可能比綜合性能更高。例如,如果key
可以用作Resp
的__init__
的第一個位置參數,但肯定不能與lambda一起使用! ( Python列表理解與地圖 )。 否則,生成器或理解力會更好:
resps = (Resp(key=k) for k, values in dic.items() if not tests.isdisjoint(values))
#resps = [Resp(key=k) for k, values in dic.items() if not tests.isdisjoint(values)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.