python - 我认为不存在索引错误

标签 python python-2.7 matrix indexing

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/

相关文章:

python - 迭代 python 集中的单个元素

python 太多关键字参数

Python - threading.Timer 在调用 cancel() 方法后保持事件状态

python - 删除已知字符

python-2.7 - 如何从 Quandl 加入/合并两个数据框?

matlab - 根据下标获取行平均值的快速方法

r - 计算每行每组列的平均值

python - 是否可以在不使用for循环的情况下将矩阵A中的所有列与矩阵B中的每一列相乘?

python - IPython 和 REPL 在没有打印功能的情况下显示数据时表现不同

python - 用子图绘制 Pandas 数据框(子图=真): Place legend and use tight layout