假设我有一个与运行时可用的5位代码绑定的别名列表:
aliasPairs = [(12345,'bob'),(23456,'jon'),(34567,'jack'),(45678,'jill'),(89012,'steph')]
我想找到一种简洁的表达方式:用匹配的别名替换行中的id,例如: :
line = "hey there 12345!"
line = re.sub('\d{5}', value in the aliasPairs which matches the ID, line)
print line
应输出:
hey there bob!
Python专业人员如何以简洁的方式编写枚举表达式?
谢谢,欢呼!
当您对两类数据进行一对一映射时,请考虑使用字典,例如五位数代码和别名。然后,根据代码,可以轻松访问任何特定的别名:
import re
aliases = {
"12345":"bob",
"23456":"jon",
"34567":"jack",
"45678":"jill",
"89012":"steph"
}
line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: aliases[v.group()], line)
print(line)
结果:
hey there bob!
如果您将直接在代码中使用这些别名(不仅仅是从数据结构中引用),那么Enum
是一个很好的方法:
from enum import Enum
class Alias(Enum):
bob = 12345
jon = 23456
jack = 34567
jill = 45678
steph = 89012
然后使用re
看起来像:
line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: Alias(int(v.group()).name, line)
您还可以使用以下方法将该行为直接添加到Alias
Enum
:
@classmethod
def sub(cls, line):
return re.sub('\d{5}', lambda v: cls(int(v.group())).name, line)
并在使用中:
Alias.sub("hey there 12345!")
当然,"bob"
可能应该大写,但谁想要Alias.Bob
他们的代码?最好将替换文本与Enum成员名称分开,使用aenum
2更容易完成一项工作:
from aenum import Enum
import re
class Alias(Enum):
_init_ = 'value text'
bob = 12345, 'Bob'
jon = 23456, 'Jon'
jack = 34567, 'Jack'
jill = 45678, 'Jill'
steph = 89012, 'Steph'
@classmethod
def sub(cls, line):
return re.sub('\d{5}', lambda v: cls(int(v.group())).text, line)
Alias.sub('hey there 34567!')
1有关标准this answer的用法,请参阅Enum
。
2披露:我是Python stdlib Enum
,enum34
backport和Advanced Enumeration (aenum
)图书馆的作者。