【问题标题】:Index error where I think there isn't我认为没有的索引错误
【发布时间】:2013-12-02 00:20:25
【问题描述】:
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: 列表赋值索引超出范围

我正在尝试制作一个以 y 为列、x 为行的矩阵。我尝试了 for 循环,while 循环......几乎所有内容,有人可以帮助我吗?
P.S.:我还在学习中,请耐心等待。

【问题讨论】:

    标签: python python-2.7 matrix indexing


    【解决方案1】:
    x = [range(0,tamanho)]
    

    这使得x 成为一个1 元素列表,其唯一元素是tamanho 元素列表。 y 行类似。那不是你想要的。如果您想要一个 m×n 矩阵,请使用 m×n 嵌套列表:

    matrix = [[0]*n for i in xrange(m)]
    

    [0]*n 生成一个充满零的 n 元素列表,列表推导式生成一个包含 m 的列表。

    【讨论】:

    • 非常感谢!现在我意识到我的错误,好吧,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2011-12-05
    相关资源
    最近更新 更多