IndexError:列表分配索引超出范围 - Python与数组
我最近开始使用Python,我仍然是新手,语言很多。这段代码应该打印出我从多个文本文件(称为2t1,...,2t19,3t1,...,3t19)输入的系列行(例如:[47.815,47.54,48.065,57.45]),以及文件结束后的文件名称。每个文件都有(4元每行总共〜12000元的,〜80行对每个文件)IndexError:列表分配索引超出范围 - Python与数组
for i in range(2,3):
for j in range(1,19):
#Open a text file and convert the row content to float:
for line in open('[Path]/%dt%d.txt' % (i,j)):
# Ignore comments:
if not line.startswith('#'):
# Got a valid data line:
row[i][j] = [float(item) for item in line.split()]
print (row[i][j])
print (' %dt%d \n' %(i,j))
它能够做什么,我问它,只是直到80个元素必须保存2T5,然后显示此消息:
Traceback (most recent call last):
File "< tmp 1>", line 8, in < module>
row[i][j] = [float(item) for item in line.split()]
IndexError: list assignment index out of range
我真的不能找出什么问题,我想在列表中不填充到它的最大(我在网上读到它有500.000.000空格) ,我看不出什么可能是错的。当你正在处理的列表是空的时候出现这个错误,但是我重复选中并且有每个文件,但是我也尝试了 row[i][j].append(float(item) for item in line.split())
(这是最常见的错误的解决方案),它返回一个非常长的列表这:
< generator object < genexpr> at 0x000000000XXXXXXX>
(其中X是不同的数字)结束,然后有相同的错误。
P.s.如果您需要我正在处理的数据,只需询问并上传即可。
看来你的问题很简单。你可能有一个列表命名row
和你试图将值分配给不存在的指数
>>> row = []
>>> row[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
然而,如果你追加一个新的列表到排列表就像我觉得你想要做
>>> row = []
>>> row.append([1, 2, 3, 4])
>>> row
[[1, 2, 3, 4]]
>>> row[0][0]
1
这将工作正常。如果你想三重巢事情
>>> row = []
>>> row.append([[1,2,3,4]])
>>> row
[[[1, 2, 3, 4]]]
>>> row[0].append([-1, -2, -3, -4])
>>> row
[[[1, 2, 3, 4], [-1, -2, -3, -4]]]
您可以使用相同的语法
请致电今后的语言'python'而不是'Phyton' – 2014-12-03 09:00:58
你是如何开始分配'row'?显然,它没有足够的条目。 – interjay 2014-12-03 09:02:20
@interjay我没有初始化/声明它。该代码不是100%的,我就是从那里拿到它的。另外我猜python不需要声明变量(这就是我的手册所说的)。 – Protolando 2014-12-03 09:08:24