print "Qual deve ser o tamanho do tabuleiro?"
while 1:
tamanho = input()
if 1 < tamanho < 6:
print "Que o jogo comece!"
break
else:
print "Nao posso usar isso como um tabuleiro..."
numeros = tamanho*tamanho-1
x = [range(0,tamanho)]
y = [range(0,tamanho)]
i = 0
while i < tamanho:
x[i-1] = y[:]
i = i + 1
我不断收到索引错误
IndexError: list assignment index out of range
我正在尝试创建一个以 y 为列、x 为行的矩阵。我尝试了 for 循环、while 循环...几乎所有的东西,有人可以帮助我吗?
P.S.:我还在学习中,所以要有耐心。
最佳答案
x = [range(0,tamanho)]
这使得 x
成为 1 元素列表,其唯一元素是 tamanho
元素列表。 y
行类似。那不是你想要的。如果您想要一个 m×n 矩阵,请使用 m×n 嵌套列表:
matrix = [[0]*n for i in xrange(m)]
[0]*n
生成一个充满零的 n 元素列表,列表推导式生成一个包含 m
个零的列表。
关于python - 我认为不存在索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318988/