Skip to main content
 首页 » 编程设计

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

2024年10月01日6jiqing9006

我查看了有关类似问题的答案,但无法找出我的问题。我是 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.]])