简体   繁体   English

如何将作为数学表达式的字符串拆分为单独的部分(包括运算符)

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

I want to separate the digits from characters and letters and add them to a list. 我想将数字与字符和字母分开,并将它们添加到列表中。

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)

It can only append every digit in the list. 它只能追加列表中的每个数字。 The current output is ['1','+','2','2','-','3','*','4','/','5'] 当前输出为['1','+','2','2','-','3','*','4','/','5']

You can use itertools.groupby with str.isdigit as the key function: 您可以将itertools.groupbystr.isdigit用作键函数:

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

This returns: 返回:

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

You could use a regular expression: 您可以使用正则表达式:

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

Output 输出量

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

Some great solutions here using stdlib , here's a pure python try: 这里使用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']

I suggest you process the characters of the string in order (for ch in str) and either (a) add them to your list; 我建议您按顺序处理字符串的字符(对于str中的ch),然后(a)将它们添加到列表中; or (b) accumulate them into a number: 或(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