例如,我需要
listBuilder('24+3-65*2')
返回
['24', '+', '3', '-', '65', '*', '2']
我们不允许使用自定义导入函数。我必须在没有他们的情况下完成这项工作。这就是我目前所拥有的。。。你知道吗
def listBuilder(expr):
operators = ['+', '-', '*', '/', '^']
result = []
temp = []
for i in range(len(expr)):
if expr[i] in operators:
result.append(expr[i])
elif isNumber(expr[i]): #isNumber() returns true if the string can convert to float
temp += expr[i]
if expr[i+1] in operators:
tempTwo = ''.join(temp)
result.append(tempTwo)
temp = []
tempTwo = []
elif expr[i+1] == None:
break
else:
continue
return result
此时我得到一个错误,字符串索引超出了包含expr[i+1]
的行的范围。我们将非常感谢您的帮助。这件事我已经耽搁了好几个小时了。你知道吗
我提出了一个更简洁的函数版本,它避免了使用字符串标记,这在Python中更快。你知道吗
您的代码抛出了索引错误,因为在上一次迭代中,您正在检查列表末尾的位置i+1处的内容。线路
抛出错误,因为在最后一次迭代中,i是最终的列表索引,您会检查不存在的列表项。你知道吗
我不确定这是否是最好的解决方案,但在给定的情况下是有效的。你知道吗
您正在迭代列表的所有组件,包括最后一项,然后测试下一项是否是运算符。这意味着当循环到达最后一个项时,就没有其他要测试的项,因此索引错误。你知道吗
请注意,运算符永远不会出现在表达式的末尾。也就是说,你不会得到像
2+3-
这样的东西,因为这是没有意义的。因此,您可以测试除最后一项之外的所有项目:相关问题 更多 >
编程相关推荐