我有 C++ 背景,对 Python 还很陌生。我可能犯了一个简单的错误。
def make_polish(s) :
no_of_pluses = 0
polish_str = []
i = 0
for index in range(len(s)):
print s[index]
if '+' == s[index]:
no_of_pluses = no_of_pluses + 1
if '*' == s[index]:
polish_str[i] = s[index-1] """Index out of range error here."""
i = i + 1
polish_str[i] = s[index+1]
i = i + 1
polish_str[i] = '*'
i = i + 1
return polish_str
print make_polish("3*4")
请您参考如下方法:
您的列表 polish_str 总是空的。你需要做的:
polish_str.append(s[index-1])
代替:
polish_str[i] = s[index-1] # """Index out of range error here."""
i = i + 1
当您创建列表 polish_str = [] 时,它不会像在 C/C++ 中那样为其分配空间。它是一个动态数据结构。
