【问题标题】:Python: converting string to flagsPython:将字符串转换为标志
【发布时间】: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


【解决方案1】:

在较新版本的 Python 中,您可以使用字典推导:

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

KennyTM 指出,在旧版本中,您可以使用它:

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

这将为长字符串提供良好的性能,因为如果所有三个字符都出现在字符串的开头,则搜索可能会提前停止。它不需要搜索整个字符串。

【讨论】:

    【解决方案2】:

    为什么不使用frozenset(或set,如果需要可变性)?

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

    那么你可以使用

    'P' in s
    

    检查标志P是否存在。

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 2012-01-26
      相关资源
      最近更新 更多