我想将数字与字符和字母分开,并将它们添加到列表中。
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']
