可以将正则表达式用作字典中的键吗? [英] Can a regular expression be used as a key in a dictionary?
问题描述
我想创建一个字典,其中的键是正则表达式:
I want to create a dictionary where the keys are regular expressions:
d = {'a.*': some_value1, 'b.*': some_value2}
然后,当我查看字典时:
Then, when I look into the dictionary:
d['apple']
我希望苹果'apple'
与作为正则表达式的键匹配.如果与key/regular-expression完全匹配,则应返回相应的值.
I want apple 'apple'
to be matched against the keys which are regular expressions. If there is a complete match with a key/regular-expression then the corresponding value should be returned.
例如'apple'
与正则表达式'a.*'
完全匹配,因此,应返回some_value1
.
For example 'apple'
matches with the regular expression 'a.*'
completely, and so, some_value1
should be returned.
当然,所有这一切都假定正则表达式键不冲突(即,两个键不应都完全匹配相同的字符串).假设我在构建密钥时可以手动满足此要求.
Of course, all of this assumes that the regular expression keys do not conflict (i.e. two keys should not both match the same string exactly). Let's say I can manually take care of this requirement when building my keys.
这在Python中可行吗?如果是这样,那将是一个相当优雅而强大的构造!
Is this possible in Python? If so, it would be quite an elegant and powerful construct!
推荐答案
Python字典实现为哈希表-这意味着通过内部散列myvalue
来进行任何mydict[myvalue]
查找都非常快.使用正则表达式作为键将取消此功能.而不是使用字典,您应该使用简单的列表或元组,其中每个项目都是格式为(pattern/compiled regular expression, value)
的元组,并对其进行扫描,直到通过正则表达式为止.这也使您能够按正则表达式的顺序进行操作(例如,从特定到通用):
Python dictionaries are implemented as hash tables - which means any mydict[myvalue]
lookup is very fast by internally hashing myvalue
. Using regular expressions as keys will cancel this functionality. Instead of using a dictionary, you should use a simple list or tuple where each item is a tuple in the format: (pattern/compiled regular expression, value)
and scan them until a regular expression passes. This will also give you the ability to play with the order of regular expressions (from specific to general, for example):
import re
LOOKUPS = [
('a.*', 'a'),
('b.*', 'b'),
]
def lookup(s, lookups):
for pattern, value in lookups:
if re.search(pattern, s):
return value
return None
print(lookup("apple", LOOKUPS))
另请参阅Django的 URL解析器(非常)高级实施您的想法.
See also Django's url resolver for a (very) advanced implementation of your idea.
这篇关于可以将正则表达式用作字典中的键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!