python - 列表分配索引超出二维数组错误的范围

标签 python list

我查看了类似问题的答案,但无法找出我的问题。我是 python 新手,请帮忙。

length = 13
breadth = 24
sheet = [ [ 0 for y in range( length ) ] for x in range( breadth ) ]
sheet[length-2][breadth-3] = 1

上面的代码给了我列表分配索引超出范围的错误。

最佳答案

您的轴混淆了,请尝试使用

sheet[breadth-3][length-2] = 1

或者,您可以使用 numpy 更优雅地完成此操作:

import numpy as np

breadth = 5
length = 3

sheet = np.zeros(shape=(breadth, length))
sheet[breadth-3, length-2] = 1

sheet.shape
>>> (5, 3)

sheet
>>> array([[ 0.,  0.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  1.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  0.,  0.]])

关于python - 列表分配索引超出二维数组错误的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293151/

相关文章:

python - 每个元素的反转计数

python - 当反向关系上的 full=True 时,Django Tastypie 抛出 'maximum recursion depth exceeded'。

python - 在 Networkx 中映射两个图

python - 如何从python中的两个列表中创建字典列表

python - 如何导入和/或引用与内置 Python 名称同名的用户定义模块

python - 我需要在最后一个位置打印不带逗号

python - 从列表中删除随机项目

c# - 比较 2 个列表的值 C#

python - python中列表的高效缩减

python - 查找(开始:end) positions that sublists occur within a list . Python