[英]How to split the integers and Operators characters from string in python?
我想將字符串拆分為整數和運算符,以便在python中執行Infix表達式求值。
這是我的字符串:
>>> s = (1-2+3)*5+10/2
我試圖這樣做:
>>>list(s)
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '1', '0', '/', '2']
錯了 由於“ 10”被分成“ 1”,因此“ 0”
我嘗試了替代方法:
>>> re.findall('[+-/*//()]+|\d+',s)
['(', '1', '-', '2', '+', '3', ')*', '5', '+', '10', '/', '2']
這也是錯的。 由於應將')*'拆分為')',因此'*'
您能幫忙從給定的表達式中拆分運算符和整數嗎?
這不是中綴的最佳解決方案。 刪除[]之后的+,例如:
import re
s = "(1-2+3)*5+10/2"
print re.findall('[+-/*//()]|\d+',s)
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '10', '/', '2']
請嘗試以下鏈接以獲取正確的解決方案: 簡單的圓括號
from pythonds.basic.stack import Stack
def postfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
def doMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
print(postfixEval('7 8 + 3 2 + /'))
請記住,這是一個后綴實現,僅作為示例。 自己做中綴,如果有任何困難,只問一下。
嘗試
re.findall('[+-/*//()]|\d+',s)
您不需要+
,因為您只想有一個特殊符號。
使用拆分:
print filter(lambda x: x, re.split(r'([-+*/()])|\s+', s))
如果可以避免使用正則表達式,則可以嘗試迭代解決方案(僅是粗略的代碼):
s = "(1-2+3)*5+10/2"
numbers = "0123456789."
def split_operators(s):
l = []
last_number = ""
for c in s:
if c in numbers:
last_number += c
else:
if last_number:
l.append(last_number)
last_number = ""
if c:
l.append(c)
if last_number:
l.append(last_number)
return l
print split_operators(s)
結果:
['(', '1', '-', '2', '+', '3', ')', '*', '5', '+', '10', '/', '2']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.