[英]Why is my list assignment index out of range in my python app?
So imagine I have this code in python: 因此,想象一下我在python中有以下代码:
import pickle
import numpy as np
import pandas as pd
x_u = []
load_model = open('dt.plk', 'rb')
dt = pickle.load(load_model)
cuantos = int(input('cuantas observaciones: '))
x_u[0] =pd.DataFrame(np.random.randint(341, size = 1))
x_u[1] =pd.DataFrame(np.random.randint(291, size = 1))
x_u[2] =pd.DataFrame(np.random.randint(150, size = 1))
x_u[3] =pd.DataFrame(np.random.randint(301, size = 1))
x_u[4] =pd.DataFrame(np.random.randint(341, size = 1))
x_u[5] =pd.DataFrame(np.random.randint(299, size = 1))
x_u[6] =pd.DataFrame(np.random.randint(150, size = 1))
x_u[7] =pd.DataFrame(np.random.randint(301, size = 1))
ps = dt.predict(x_u)
for d in x_u[0].tolist():
if d == 0:
print('Se queda')
else:
print('Se va')
When I run it I get this error. 当我运行它时,出现此错误。 I've been modifying the index range with no success can you figure out what it is? 我一直在修改索引范围,但没有成功,您能弄清楚它是什么吗?
Traceback (most recent call last):
File "app.py", line 8, in <module>
x_u[0] =pd.DataFrame(np.random.randint(341, size = 1))
IndexError: list assignment index out of range
You're trying to assign a value to a list index that doesn't exist. 您试图将一个值分配给一个不存在的列表索引。
If you simply want to assign to those index values in order, you can use .append()
: 如果只想按顺序分配这些索引值,则可以使用.append()
:
list.append(x) Add an item to the end of the list. list.append(x)将一个项目添加到列表的末尾。 Equivalent to a[len(a):] = [x]. 等效于a [len(a):] = [x]。
Thusly modified, your code might look like this: 这样修改后,您的代码可能如下所示:
import pickle
import numpy as np
import pandas as pd
x_u = []
load_model = open('dt.plk', 'rb')
dt = pickle.load(load_model)
cuantos = int(input('cuantas observaciones: '))
x_u.append(pd.DataFrame(np.random.randint(341, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(291, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(150, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(301, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(341, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(299, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(150, size = 1)))
x_u.append(pd.DataFrame(np.random.randint(301, size = 1)))
ps = dt.predict(x_u)
for d in x_u[0].tolist():
if d == 0:
print('Se queda')
else:
print('Se va')
Of course, without your input file, and desired input/output, it's hard to tell if this is what you desire. 当然,如果没有输入文件和所需的输入/输出,则很难确定这是否是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.