【发布时间】:2011-02-20 23:31:36
【问题描述】:
如果我有一个字符串是匹配正则表达式[MSP]* 的输出,那么将它转换为包含键 M、S 和 P 的 dict 的最简洁方法是什么,如果键出现,每个键的值都是 true在字符串中?
例如
'MSP' => {'M': True, 'S': True, 'P': True}
'PMMM' => {'M': True, 'S': False, 'P': True}
'' => {'M': False, 'S': False, 'P': False}
'MOO' won't occur...
if it was the input to matching the regexp, 'M' would be the output
我能想到的最好的是:
result = {'M': False, 'S': False, 'P': False}
if (matchstring):
for c in matchstring:
result[c] = True
但这似乎有点笨拙,我想知道是否有更好的方法。
【问题讨论】:
-
这真的是最有用/可读的数据结构吗?看起来简单的
'M' in test_string检查可能更具可读性。 -
这就是我问的原因...保留原始字符串是我想避免的事情,我只是想总结一下。
标签: python string dictionary