2014-09-25 45 views
-3

我找不到任何好的算法來壓扁dict中給出的值。我的表達式是一個帶有「變量」的字符串。每個變量可以是一個數字或另一個變量即: 我的字典是拼合表達式算法

map = { 
    'a': 4, 
    'b': 6, 
    'c': 'a+b', 
    'd': 'c+a+4' 
} 

和表達可以是這樣的:

first = 'a + b' # result should be: '4 + 6'

secound = 'd PLUS c' # result '4+6+4+4 PLUS 4+6'

我不想評價這個結果。我不知道如何更換(扁平化?)的實數,變量(從地圖字典)

回答

2

使用正則表達式替換(re.subRegexpObject.sub其接受不只是一個替換字符串,而且替換功能作爲第二個參數):

import re 

def flatten(expression, mapping): 
    pattern = re.compile('|'.join(map(re.escape, mapping))) 
    while pattern.search(expression): 
     expression = pattern.sub(lambda m: mapping[m.group()], expression) 
    return expression 

mapping = { 
    'a': 4, 
    'b': 6, 
    'c': 'a+b', 
    'd': 'c+a+4' 
} 

# Convert all values to strings. 
mapping = {key: str(mapping[key]) for key in mapping} 

用法:

>>> flatten('a + b', mapping) 
'4 + 6' 
>>> flatten('d PLUS c', mapping) 
'4+6+4+4 PLUS 4+6' 

BTW,不要使用map作爲變量名。它會陰影內置功能map