Skip to main content
 首页 » 编程设计

python之将表达式解析为列表

2025年05月04日18zhoujg

我得到一个使用括号和 + 的表达式,例如 (((a+b)+c)+(d+e)).

我需要找到这个解析树,然后打印这个解析树的列表形式,比如: [ [ [a, b], c ], [d, e] ]

我在想我会使用像 ast 这样的东西,然后是 ast2list。但是,由于我没有完全理解这些,我反复出现语法错误。这是我的:

import ast 
import parser 
 
a = ast.parse("(((a+b)+c)+(d+e))", mode='eval') 
b = parser.ast2list(a) 
 
 
print(b) 

谁能指导我正确的方向?谢谢。

请您参考如下方法:

Colleen 的评论可以通过以下方式实现:

str = "(((a+b)+c)+(d+e))" 
 
 
replacements = [ 
    ('(','['), 
    (')',']'), 
    ('+',','), 
    # If a,b,c,d,e are defined variables, you don't need the following 5 lines 
    ('a',"'a'"), 
    ('b',"'b'"), 
    ('c',"'c'"), 
    ('d',"'d'"), 
    ('e',"'e'"), 
] 
 
for (f,s) in replacements: 
    str = str.replace(f,s) 
 
obj = eval(str) 
 
print(str)       # [[['a','b'],'c'],['d','e']] 
print(obj)       # [[['a', 'b'], 'c'], ['d', 'e']] 
# You can access the parsed elements as you would any iterable: 
print(obj[0])    # [['a', 'b'], 'c'] 
print(obj[1])    # ['d', 'e'] 
print(obj[1][0]) # d