我有一个逻辑表达式,如:
expression = '(1 & 2) & 3'
and a dictionary as,x = {1: '1',2: '0',3: '0'}
--- keys can be int or string,manageable
我需要将此字符串评估为
'(1 & 2) & 3'
=> '(x[1] & x[2]) & x[3]'
=> '(1 & 0) & 0'
=> eval('(1 & 0) & 0') = 0
我目前正在这样做:
re.sub('(\d+)',r'x[\1]',expression)
=> '(x[1] & x[2]) & x[3]'
but can't run eval on this
或
re.sub('(\d+)',eval(r'x[\1]'),expression)
=> eval(x[\1]) --> logical error
请分享一个有效的解决方案以实现此目标。该应用程序可以定义不同的表达式,并且一个表达式用于评估1000多种字典,例如x。