开发者

Python: converting string to flags

If I have a string that is the output of matching the regexp [MSP]*, what's the cleanest way to convert it to a dict containing keys M, S, and P where the value of each key is true if the key appears in the string?

e.g.

 '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

The best I can come up with is:

 result = {'M': False, 'S': False, 'P': False}
 if (matchstring):
     for c in matchstring:
         result[c] = True

but this seems slightly clunky, I wondered if there was a better w开发者_如何转开发ay.


Why not use a frozenset (or set if mutability is needed)?

s = frozenset('PMMM')
# now s == frozenset({'P', 'M'})

then you can use

'P' in s

to check whether the flag P exists.


In newer versions of Python you can use a dict comprehension:

s = 'MMSMSS'
d = { c: c in s for c in 'MSP' }

In older versions you can use this as KennyTM points out:

d = dict((c, c in s) for c in 'MSP')

This will give good performance for long strings because if all three characters occur at the beginning of the string the search can stop early. It won't require searching the entire string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜