问题描述
我想将中缀表达式转换为列表,以便将两位数或字符视为单个操作数,即 28*35/(21-13)
应导致 ['28','*','35','/','(','21','-','13',')']
这是我写的代码,它运行良好,但我想知道是否有更聪明的方法来做到这一点,比如列表理解或其他东西
expression = "28*35/(21-13)"
expression.replace(' ','') # replace spaces if any
expressionList = []
operand = ""
for char in expression:
if char in "+-*/()":
if operand != '':
expressionList.append(operand)
operand = ''
expressionList.append(char)
else:
operand += char
解决方法
您不能使用 list-comprehension
作为需要知道前一个元素来拆分内容。我看到的更简单的解决方案是使用 regex
这里的 (\d+|[-+()/*])
表示
-
\d+
任何一组数字,或(竖线是 OR|
) -
-+()/*
中的任何字符
import re
expression = "28*35/(21-13)"
values = re.findall(r"(\d+|[-+()/*])",expression)
print(values) # ['28','*','35','/','(','21','-','13',')']
添加字母:"([A-Z]+|\d+|[-+()/*])"