为什么这个python程序中有运行时错误?

qqq*_*qqq 1 python

我有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")
Run Code Online (Sandbox Code Playgroud)

war*_*iuc 8

您的列表polish_str始终为空.你需要这样做:

polish_str.append(s[index-1])
Run Code Online (Sandbox Code Playgroud)

代替:

polish_str[i] = s[index-1] # """Index out of range error here."""
i = i + 1 
Run Code Online (Sandbox Code Playgroud)

当你创建列表时,polish_str = []它没有像在C/C++中那样为它分配空间.这是一个动态的数据结构.