展平表达式算法

2024-04-26 08:06:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到任何好的算法来压平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'

我不想评估这个结果。我想知道如何替换(压平?)实数形式的变量(来自map dict)


Tags: 字符串算法map字典表达式plus数字be
1条回答
网友
1楼 · 发布于 2024-04-26 08:06:34

使用正则表达式替换(^{}^{}),它不仅接受替换字符串,还接受替换函数作为第二个参数):

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'

顺便说一句,不要使用map作为变量名。它将隐藏内置函数map。你知道吗

相关问题 更多 >