[英]Python list assignment out of range after initializing multidimensional list
So, I'm trying to work with multidimensional lists to make a map for an ASCII game. 所以,我正在尝试使用多维列表来制作ASCII游戏的地图。 I have code to initialize the list, 我有代码来初始化列表,
mapData = [[[0 for m in range(3)] for x in range(32)] for y in range(32)]
then I try to access and change a value in the variable using this code, 然后我尝试使用此代码访问和更改变量中的值,
mapData[0][5][5] = 1
and get this error message, 并收到此错误消息,
IndexError: list assignment index out of range
I've tried many things, but can't figure anything out. 我尝试了很多东西,但无法解决任何问题。
Your innermost list has only three cells, so trying to access [5]
on it won't work. 你最里面的列表只有三个单元格,所以试图访问它[5]
是行不通的。
The indices go from outermost (with 32 entries) to innermost (with 3 entries). 索引从最外层(有32个条目)到最里面(有3个条目)。 If you expected your innermost list to have 6 or more cells, you need to adjust your for m in range(3)
loop. 如果您希望最里面的列表包含6个或更多单元格,则需要for m in range(3)
循环中调整for m in range(3)
。
If you expected to index the first cell of the innermost list, perhaps you needed to reverse the indices: 如果您希望索引最里面列表的第一个单元格,也许您需要反转索引:
mapData[5][5][0] = 1
To spell it out some more: 再解释一下:
mapData[0]
returns the first element of the outermost list, generated by the for y in range(32)
loop in your nested list comprehensions. mapData[0]
返回最外层列表的第一个元素,由嵌套列表mapData[0]
的for y in range(32)
循环生成。 [5]
in mapData[0][5]
then accesses the 6th element of the previous result, a list from the for x in range(32)
loop. [5]
在mapData[0][5]
然后访问先前结果的第六元件,从所述列表for x in range(32)
循环。 [5]
in mapData[0][5][5]
tries to index the innermost list, one of the list objects generated by [0 for m in range(3)]
. [5]
在mapData[0][5][5]
试图索引的最内列表中,所产生的列表中的对象中的一个[0 for m in range(3)]
。 Because those lists only have 3 0
values each, an IndexError
exception is raised. 因为这些列表每个只有3 0
值,所以会引发IndexError
异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.