2010-05-18 110 views
2

如果我有一個字符串是與正則表達式[MSP]*匹配的輸出,那麼將其轉換爲包含M,S和P鍵的字典的最簡潔方法是什麼?其中每個鍵的值都是true如果密鑰出現在字符串中?Python:將字符串轉換爲標誌

例如

'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 

但這似乎略顯笨重,我想知道是否有更好的方法。

+0

這真的是最有用/可讀的數據結構嗎?這似乎是一個簡單的''test_string'中的'M'檢查可能更具可讀性。 – 2010-05-18 15:59:25

+0

這就是爲什麼我問...保持原始字符串是我想避免的,我只想總結一下。 – 2010-05-18 16:11:23

回答

6

爲什麼不使用frozenset(或set如果需要可變性)?

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

那麼你可以使用

'P' in s 

檢查標誌P是否存在。

+0

有趣......謝謝! – 2010-05-18 15:59:06

3

在Python的新版本,你可以使用字典理解:

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

在舊版本中,你可以使用它作爲KennyTM指出:

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

這將給予長串性能好因爲如果所有三個字符都出現在字符串的開頭,搜索可以提前停止。它不需要搜索整個字符串。

+2

'd = dict((c,s in c)for'in'MSP')',適用於Python 2.6。 – kennytm 2010-05-18 15:59:36