我需要创建一个字典,其中的键将是一个正则表达式。我想将一个值与不同的键进行比较。例如,我希望这些键具有相同的值:
int(1), int(2) ... int(10)
并不是每个人都创建密钥,我需要为所有可能的密钥使用一个正则表达式。我怎样才能做到这一点?
字典的近似示例:
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 ')
和
>>> print type_field[1]
int (10)
我想直接使用key来吸引字典的值type_field[1]
,而不需要循环。像这样:
di[type_field[1]]
int(number)
从1到11之间的任何数字,我都会收到相同的值。是否有可能?
如果从字面上讲是regex的键,则它们是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 ')]
除此之外,您可能需要创建一个类来做更专门的事情。根据您的描述,我认为您仍然需要多考虑一些细节。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句