簡體   English   中英

如何將作為數學表達式的字符串拆分為單獨的部分(包括運算符)

[英]How to split string that is a mathematical expression into separate parts (including operators)

我想將數字與字符和字母分開,並將它們添加到列表中。

n = "1+22-3*4/5"
eq=list(n)
c=0
for i in eq:
  if "*" in eq:
    while "*" in eq:
      c=eq.index("*")
      eq[c-1]=float(eq[c-1])*float(eq[c+1])
      del eq[c]
      del eq[c]
      print(eq)
  if "/" in eq:
    while "/" in eq:
      c=eq.index("/")
      eq[c-1]=float(eq[c-1])/float(eq[c+1])
      del eq[c]
      del eq[c]
      print(eq)
  if "+" in eq:
    while "+" in eq:
      c=eq.index("+")
      eq[c-1]=float(eq[c-1])+float(eq[c+1])
      del eq[c]
      del eq[c]
      print(eq)
  if "-" in eq:
    while "-" in eq:
      c=eq.index("-")
      eq[c-1]=float(eq[c-1])-float(eq[c+1])
      del eq[c]
      del eq[c]
  print(eq)
print(n,"=",eq)

它只能追加列表中的每個數字。 當前輸出為['1','+','2','2','-','3','*','4','/','5']

您可以將itertools.groupbystr.isdigit用作鍵函數:

from itertools import groupby
[''.join(g) for _, g in groupby(n, key=str.isdigit)]

返回:

['1', '+', '22', '-', '3', '*', '4', '/', '5']

您可以使用正則表達式:

import re
s = "1+22-3*4/5"
re.split('(\W)', s)

輸出量

['1', '+', '22', '-', '3', '*', '4', '/', '5']

這里使用stdlib一些很棒的解決方案,這是一個純python嘗試:

i = "11+11*11"

def parser(i):
  out = []
  gram = []
  for x in i:
    if x.isdigit():
      gram.append(x)
    else:
      out.append("".join(gram))
      out.append(x)
      gram = []
  if gram:
    out.append("".join(gram))
  return out

parser(i) # ['11', '+', '11', '*', '11']

我建議您按順序處理字符串的字符(對於str中的ch),然后(a)將它們添加到列表中; 或(b)將它們累加成一個數字:

str = "1+22-3*4/5"
tokens = []
number = None
operators = "+-*/"
digits = "0123456789"

for ch in str:
    if ch in operators:
        if number is not None:
            tokens.append(number)
        tokens.append(ch)
        continue
    elif ch in digits:
        if number is None:
            number = ch
        else:
            number += ch
        continue
    else:
        # what else could it be?
        pass

# After loop, check for number at end 
if number is not None:
   tokens.append(number)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM