Skip to main content
 首页 » 编程设计

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

2025年05月04日14xxx_UU

我想将数字与字符和字母分开,并将它们添加到列表中。

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.groupby 和 str.isdigit 作为键函数:

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

返回:

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