2016-04-14 28 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()