我在创建对象时遇到问题,其中2D数组的长度可变。我不断出错
self.state[i] = listt[i]
IndexError: list assignment index out of range
如果我尝试创建具有2行3列的数组的对象,则它可以工作。如果我尝试创建具有3行3列的对象,它将失败并显示错误。
class node:
def __init__(self, m, n, listt=None):
self.not_in_place = -1
self.m = m
self.n = n
self.state = [[m],[n]]
if listt is not None:
for i in range(self.m):
self.state[i] = listt[i]
start = [[0,1,2],[3,4,5],[6,7,8]]
node(3, 3, start) # doesn't work
start_2 = [[0,1,2],[3,4,5]]
node(2, 3, start_2) # work
我究竟做错了什么 ?
在python中,您不能通过给定大小来初始化具有给定大小的数组,也不需要
要将给定列表分配给state
,请执行以下操作将其复制
if listt is not None:
self.state = list(listt)
它在第二种情况下起作用的原因是,您创建了一个包含2个子列表的列表,因此创建了2个框,当您遍历它们时还可以,并且尝试长度为3时也失败了
state = [[2], [3]] # [[2], [3]], and not [[,,], [,,]]
如果要初始化为空,如果listt
为无,则可以
class node:
def __init__(self, m, n, listt=None):
self.not_in_place = -1
self.m = m
self.n = n
self.state = [[]] * m
if listt is not None:
self.state = list(listt)
def __str__(self):
return str(self.state)
if __name__ == '__main__':
start = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
n = node(3, 3, start)
print(n) # [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
n = node(2, 3, None)
print(n) # [[], []]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句