假设我有一个别名列表,它与运行时可用的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专业人士如何以简洁的方式编写枚举表达式?你知道吗
谢谢,干杯!你知道吗
当您有两类数据(例如五位数代码和别名)的一对一映射时,请考虑使用字典。然后,根据其代码,很容易访问任何特定别名:
结果:
如果您将在代码中直接使用这些别名(而不仅仅是从数据结构引用),那么
Enum
是一个很好的方法:然后使用
re
看起来像:您还可以使用以下方法将该行为直接添加到
Alias
Enum
:使用中:
当然,} 2更容易完成这项工作:
"bob"
可能应该大写,但是谁想让Alias.Bob
布满他们的代码呢?最好将替换文本与枚举成员名称分开,使用^{1参见this answer了解标准
Enum
用法。你知道吗披露:我是Python stdlib ^{} 、^{} backport 和Advanced Enumeration (^{}) 库的作者。你知道吗
相关问题 更多 >
编程相关推荐