简体   繁体   English

列表分配索引超出范围

[英]List assignment index out of range

My code is giving me the error of: 我的代码给我以下错误:

    list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range.

I have searched for this error and i still can't find what is the problem. 我已经搜索了此错误,但仍然找不到问题所在。

Edit: Full Traceback 编辑:完全回溯

Traceback (most recent call last): File "", line 420, in run_nodebug File "C:\\Documents and Settings\\jhsilva\\Desktop\\Monte carlo\\Teste.py", line 71, in generateRandomNumbers(list_subs) File "C:\\Documents and Settings\\jhsilva\\Desktop\\Monte carlo\\Teste.py", line 41, in generateRandomNumbers list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2]) IndexError: list assignment index out of range 追溯(最近一次通话最新):run_nodebug中的文件“”,第420行,generateRandomNumbers(list_subs)文件中的文件“ C:\\ Documents and Settings \\ jhsilva \\ Desktop \\ Monte carlo \\ Teste.py”,行71,“ C: \\ Documents and Settings \\ jhsilva \\ Desktop \\ Monte carlo \\ Teste.py“,第41行,位于generateRandomNumbers list_subs [n] [4] = np.random.normal(list_subs [n] [1],list_subs [n] [2 ])IndexError:列表分配索引超出范围

The Code 编码

def generateRandomNumbers(list_subs):

    for n in range(len(list_subs)):

        string = list_subs[n][3]
        string = string.lower()

        if(string == "normal"):
            list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
            print("Numero gerado:",list_subs[n][4])


variables = [v for v in variables if v not in special]


list_subs=[[0 for col in range(6)] for row in range(len(variables)-1)]

#This prints fine
print(len(list_subs))

#this prints fine too
print(list_subs[0][4])

for n in range(len(variables)):
    if n>0:
        (media,desviopadrao,distribuicao) = eval(input("For variable "+variables[n]+" input: median, std, distr \n"))
        list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]

N = eval(input("Qual o numero de iteracoes que deseja:"))

Var = []
for n in range(N):
    generateRandomNumbers(list_subs)
    Var.append(calcEq(formula))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]

You are setting list_subs to be a list of lists of length 4 . 您将list_subs设置为长度为4的列表的列表。 This means that the valid indeces are 0, 1, 2, 3 . 这意味着有效指数为0, 1, 2, 3 In generateRandomNumbers you access index 4 , which is invalid. generateRandomNumbers您访问索引4 ,这是无效的。


Security note: Don't use eval(input(...)) . 安全说明:不要使用eval(input(...)) If you want to parse numbers/tuples etc simply use ast.literal_eval , which is a safe alternative. 如果要解析数字/元组等,只需使用ast.literal_eval ,这是一个安全的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM