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