簡體   English   中英

在python字典中執行多重匹配查找的最有效方法是什么?

[英]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。 願意給它盡可能多的內存。

考慮將兩個字典查找放在單獨的進程中以加快速度(這有意義嗎?)。 歡迎其他任何優化想法


  • 值絕對可以排序並變成一個集合; 它是預先計算的,非常大。
  • 總是len(values)>>>> len(tests),盡管它們都隨着時間而增長
  • len(tests)增長非常非常緩慢,並且每次執行都有新的值
  • 當前正在查看字符串(考慮進行字符串->整數映射)

對於初學者來說,當您已經在使用列表推導時,沒有理由使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM