python中的字典键是RegExp

用户名

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

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之间的任何数字,我都会收到相同的值。是否有可能?

w

如果从字面上讲是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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

字典中的条件键-python

来自分类Dev

字典中的python相似键

来自分类Dev

python字典中的重复键

来自分类Dev

当键是Python中字典中的元组时

来自分类Dev

在Python中的字典中添加缺少的键

来自分类Dev

在Python中从字典中删除键

来自分类Dev

如何从Python字典中删除键?

来自分类Dev

所有字典中的Python打印键

来自分类Dev

从字典python列表中查找键的值

来自分类Dev

使用列表作为Python字典中的键

来自分类Dev

python中的部分匹配字典键(元组)

来自分类Dev

python中具有多个键的字典

来自分类Dev

Python用字典中的值替换键

来自分类Dev

Python字典替换键中的空格

来自分类Dev

Python字典中的键/值混淆

来自分类Dev

在Python字典中搜索匹配键

来自分类Dev

合并Python中相同键的字典

来自分类Dev

在字典python中添加键的列表值

来自分类Dev

解析python字典中相同键的值

来自分类Dev

盒从python中的字典键绘制数据

来自分类Dev

如何从Python字典中删除键?

来自分类Dev

字典键*值到python中的列表

来自分类Dev

在Python字典中截断键长

来自分类Dev

从python中的不同字典获取通用键

来自分类Dev

在python字典中修改键的名称

来自分类Dev

从Python中的字典键获取值

来自分类Dev

Python Dict:在字典列表中查找键

来自分类Dev

在python中检查键,嵌套字典的值?

来自分类Dev

元组列表作为Python中字典的键