Skip to main content
 首页 » 编程设计

python之python 中的字典键是 RegExp

2024年10月25日11jyk

我需要创建一个字典,其中的键是一个正则表达式。我想将一个值与不同的键进行比较。例如,我希望这些键具有相同的值:

int(1), int(2) ... int(10)  

这不是让每个人都可以创建 key ,我需要为所有可能的 key 创建一个正则表达式。我该怎么做?

字典的大概例子:

dict = {'int([0-9]*)': 128, 'tinyint([0-9]*)': 64} 

我可以不用循环吗?

我在MYSQL中检查没有达到限制值。该字段的限制 - 始终相同。类型字段可以是 int(1), int(2)...int(11)

我正在从 MYSQL 值获取元组中字段的类型:

type_field = (u'number', u'int (10)', u'NO', u'PRI', None, u'auto_increment')

和

>>> 打印 type_field[1]

int (10)

我想通过keytype_field[1]直接求字典的值,没有循环。像这样:

di[type_field[1]]

对于 int(number) 中从 1 到 11 的任何数字,我都会收到相同的值。可能吗?

请您参考如下方法:

如果您的字面意思是正则表达式的键,它们是 Python 中的可哈希对象:

>>> {re.compile(r'int([0-9]*)'): 128} 
{<_sre.SRE_Pattern object at 0x10cbd6200>: 128} 

这意味着您可以执行以下操作:

>>> di={re.compile(r'a'): 'ay in there', re.compile('b'): 'bees in there'} 
>>> for s in ('say', 'what', 'you', 'mean', 'bag'): 
...     print s, [di[k] for k in di if k.search(s)] 
...  
say ['ay in there'] 
what ['ay in there'] 
you [] 
mean ['ay in there'] 
bag ['ay in there', 'bees in there'] 

或者在使用之前使用代表正则表达式的字符串:

>>> di={r'^\w\w?a': '"a" is second or third letter' , r'^[^aeiou][aeiou]': "vowel after non-vowel"} 
>>> for s in ('aaa', 'bag', 'box', 'drag'): 
...     print s, [di[k] for k in di if re.search(k, s)] 
...  
aaa ['"a" is second or third letter'] 
bag ['vowel after non-vowel', '"a" is second or third letter'] 
box ['vowel after non-vowel'] 
drag ['"a" is second or third letter'] 

根据您的更新,在我看来您正在寻找列表理解:

li=[ 
(u'number ', u'int (10)', u'NO ', u'PRI', None, u'auto_increment '), 
(u'number ', u'int (22)', u'NO ', u'PRI', None, u'auto_increment '), 
(u'number ', u'int (11)', u'NO ', u'PRI', None, u'auto_increment '), 
] 
 
>>> [e for e in li if 1<int(re.search(r'\((\d+)\)$', str(e[1])).group(1))<11] 
[(u'number ', u'int (10)', u'NO ', u'PRI', None, u'auto_increment ')] 

除此之外,您可能需要创建一个类来做一些更专业的事情。根据您的描述,我认为您仍然需要更多地考虑细节。