Jas*_*n S 2 python string dictionary
如果我的字符串是匹配正则表达式的输出[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
Run Code Online (Sandbox Code Playgroud)
我能想到的最好的是:
result = {'M': False, 'S': False, 'P': False}
if (matchstring):
for c in matchstring:
result[c] = True
Run Code Online (Sandbox Code Playgroud)
但这看起来有点笨重,我想知道是否有更好的方法.
为什么不使用frozenset(或者set如果需要可变性)?
s = frozenset('PMMM')
# now s == frozenset({'P', 'M'})
Run Code Online (Sandbox Code Playgroud)
然后你可以使用
'P' in s
Run Code Online (Sandbox Code Playgroud)
检查标志是否P存在.