【问题标题】:python IndexError: list index out of rangepython IndexError:列表索引超出范围
【发布时间】:2016-08-25 12:10:13
【问题描述】:

我正在尝试从以下板上创建一个矩阵,第一项作为坐标 (0,0) 并使用以下代码,但我不断收到列表索引超出范围错误...有人可以帮我吗退出或纠正我应该如何进行?

board_5x = ['orange', 'green', 'blue', 'orange', 'red',
            'orange', 'blue', 'orange', 'orange', 'yellow',
            'blue', 'orange', 'blue', 'red', 'green',
            'yellow', 'orange', 'green', 'orange', 'red',
            'orange', 'blue', 'yellow', 'red', 'green',
            'red', 'yellow', 'blue', 'blue', 'yellow',
            'green', 'orange', 'orange', 'green', 'green',
            'orange', 'green', 'red', 'red', 'green',
            'orange', 'yellow', 'yellow', 'red', 'orange',
            'red', 'green', 'blue', 'blue', 'orange']


board=[]

for row in range(10):
    for col in range(5):      
        board[row][col]=board_5x[row*5+col]
print board

【问题讨论】:

    标签: python list indexing range out


    【解决方案1】:

    您还没有在board 中放置值,因此您不妨继续使用新值一次构建并理解:

    board = [[board_5x[row*5+col] for col in range(5)] for row in range(10)]
    

    【讨论】: