2016-04-14 30 views
2

所以我有值的列表:定義字典成員資格比較而不重載IN?

alist = list() 

而且我想請檢查列表的成員是一個字典:

ahash = dict() #imagine I have filled a dictionary with data. 

for member in alist: 
    if member in hash: 
     #DO STUFF 

這是非常簡單的。

但是我想要做的是重新定義IN來實現模糊比較。所以我想要做的就是將FOOBARBAZZ與*做匹配,使FOO *與FOOBARBAZZ匹配。

我認爲可以這樣做的最直接的方法是將這種情況作爲對象中的方法實現,然後重載IN運算符。然而,由於我自己的原因(完全迂腐),我想避免OOP方法。

沒有循環遍歷整個詞典的每一個比較(這聽起來不對!)我怎樣才能實現我的字典自定義比較?

附加: 除IN之外,IN運算符是否有不同的名稱?命名使得運營商的信息難以在搜索引擎中進行研究。我認爲它可能與__contains__相同,但我還沒有發現__contains__如何用於字典。

+0

'ahash = hash()'是一個不正確的語法! 'hash()'函數不會創建一個字典,它將返回它的輸入參數的散列值(如果它是可散列的)。 – Kasramvd

+0

我想你明白我的意思了。 – baordog

+0

因爲你要回到O(n)搜索解決方案(遠離散列表),你正在以這種方式損失很多字典的效率。如果某些內容與多個鍵匹配會怎樣返回列表?第一? –

回答

1

回答這個問題的最好方法是將alist中的任何內容都轉換爲正則表達式。那麼你可以申請)正則表達式來dict.keys(,例子可能會在這裏:

How to use re match objects in a list comprehension

是否有已經爲您的模糊匹配定義的形式語言,或者是你做一個呢?談到「富*」到能用再通過

regex = re.sub("\*", ".*", list_element) + "$" 

來完成。如果尾隨「*」是您正在使用的匹配,那麼您的解決方案將是唯一的符號:

for member in alist: 
    regex = re.sub("\*", ".*", member) + "$" 
    if any([re.match(regex, x) for x in hash.keys()]): 
    # do stuff 

如果你想爲了讓你的匹配語言更加強大,你只需要將你的翻譯成一個更復雜的正則表達式。

3

要覆蓋in你也可以繼承內置dict類型和定義一個新的__contains__方法(這是在幕後in電話):

In [9]: class FuzzyDict(dict): 
    ...:  def __contains__(self, needle): 
    ...:   if '*' not in needle: 
    ...:    return super(FuzzyDict, self).__contains__(needle) 
    ...:   else: 
    ...:    for key in self.keys(): 
    ...:     if str(key).startswith(needle[:-1]): 
    ...:      return True 
    ...:    return False 
    ...: 

這就像在很多方面一個dict

In [12]: my_dict = FuzzyDict(zip('abcde', range(1, 6))) 

In [13]: my_dict 
Out[13]: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 

In [14]: my_dict['apple'] = 6 

,直到你開始使用in測試:

In [15]: 'a' in my_dict 
Out[15]: True 

In [16]: 'a*' in my_dict 
Out[16]: True 

In [17]: 'ap*' in my_dict 
Out[17]: True 

In [18]: 'b*' in my_dict 
Out[18]: True 

In [19]: 'bi*' in my_dict 
Out[19]: False 

這是基於我在您的文章看。如果您需要支持超過foo*,那麼顯然startswith測試是不夠的,你甚至可能不得不使用正則表達式。這也只覆蓋in - 如果你想要像my_dict['FOO*']這樣的密鑰訪問,你還需要覆蓋__getitem__和朋友。

根據您的要求,我沒有看到這種方式可以在小於O(n)的範圍內完成。訪問時間爲O(1)的唯一原因是哈希,並且如果沒有整個密鑰,就無法獲得哈希。

1

至少有兩種方法可以實現您的目標。在示例A中,運行快速查詢以確定您的成員是否是散列的一部分。只要找到匹配,它就會停止。另一方面,示例B可能被證明是更有用的,因爲返回所有匹配的值。這使您可以處理與您的成員相關的散列部分,而無需運行其他查詢。

#! /usr/bin/env python3 


def main(): 
    """Demonstrate the usage of dict_contains and dict_search.""" 
    my_list = ['ist', 'out', 'ear', 'loopy'] 
    my_hash = {'a': 50, 'across': 14, 'ahash': 12, 'alist': 31, 'an': 73, 
       'and': 11, 'are': 2, 'as': 34, 'avoid': 82, 'be': 3, 
       'besides': 49, 'but': 45, 'can': 32, 'check': 51, 'come': 84, 
       'comparison': 40, 'custom': 61, 'dictionary': 58, 
       'different': 76, 'difficult': 85, 'do': 86, 'does': 13, 
       'entire': 37, 'every': 33, 'filled': 77, 'foobarbazz': 20, 
       'for': 42, 'fuzzy': 53, 'have': 30, 'how': 36, 'however': 68, 
       'i': 74, 'if': 43, 'implement': 62, 'in': 57, 'information': 46, 
       'is': 71, 'it': 83, 'like': 64, 'list': 55, 'looping': 70, 
       'makes': 63, 'match': 16, 'matches': 1, 'member': 29, 
       'members': 78, 'method': 7, 'might': 6, 'most': 28, 'my': 38, 
       'name': 18, 'naming': 41, 'of': 52, 'on': 17, 'oop': 35, 
       'operator': 21, 'over': 19, 'overload': 27, 'own': 72, 
       'reasons': 79, 'redefine': 10, 'research': 22, 'same': 48, 
       'search': 75, 'see': 5, 'situation': 39, 'so': 87, 'sounds': 24, 
       'straightforward': 69, 'stuff': 15, 'such': 66, 'that': 47, 
       'the': 56, 'then': 54, 'things': 81, 'think': 67, 'this': 59, 
       'to': 9, 'very': 0, 'want': 23, 'way': 60, 'what': 44, 
       'whole': 26, 'with': 8, 'without': 65, 'works': 4, 'would': 25, 
       'yet': 80} 
    # Example A 
    for member in my_list: 
     if dict_contains(my_hash, member): 
      print('Found:', member) 
    # Example B 
    for member in my_list: 
     match = dict_search(my_hash, member) 
     if match: 
      print('Query with', member, 'resulted in', match) 
     else: 
      print('Searching with', member, 'failed miserably') 


def dict_contains(self, needle): 
    """Check if search term can be found in any key of the given dict.""" 
    return any(needle in haystack for haystack in self) 


def dict_search(self, pattern): 
    """Return the dict's subset where the search term is found in the key.""" 
    return {key: value for key, value in self.items() if pattern in key} 


if __name__ == '__main__': 
    main()