Hashtable/dictionary/map lookup with regular expressions

前端 未结 19 1546
难免孤独
难免孤独 2021-02-01 05:36

I\'m trying to figure out if there\'s a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the

19条回答
  •  误落风尘
    2021-02-01 06:34

    What about the following:

    class redict(dict):
    def __init__(self, d):
        dict.__init__(self, d)
    
    def __getitem__(self, regex):
        r = re.compile(regex)
        mkeys = filter(r.match, self.keys())
        for i in mkeys:
            yield dict.__getitem__(self, i)
    

    It's basically a subclass of the dict type in Python. With this you can supply a regular expression as a key, and the values of all keys that match this regex are returned in an iterable fashion using yield.

    With this you can do the following:

    >>> keys = ["a", "b", "c", "ab", "ce", "de"]
    >>> vals = range(0,len(keys))
    >>> red = redict(zip(keys, vals))
    >>> for i in red[r"^.e$"]:
    ...     print i
    ... 
    5
    4
    >>>
    

提交回复
热议问题