[英]Handling out of range list index in Python 2.7
I have a list of lists in Python 2.7, just like the one shown below 我在Python 2.7中有一个列表列表,就像下面显示的那样
rr =[[10 for row in range(5)] for col in range(5)]
Now, in my algorithm, where I need to find the neighbours of a given list element, I used the following way of checking for neighbours 现在,在我的算法中,我需要找到给定列表元素的邻居,我使用以下方法检查邻居
b = [rr[rn][cn+1],rr[rn-1][cn+1],rr[rn-1][cn],rr[rn-1][cn-1],rr[rn][cn-1],rr[rn+1][cn-1],rr[rn+1][cn],rr[rn+1][cn+1]]
I want to assign 0
to the neighbouring elements that are outside the boundary of the given matrix (or list) 我想将
0
分配给给定矩阵(或列表)的边界之外的相邻元素
where rn
is the row index, and cn
is the column index of the list cell that I wanted to inspect. 其中
rn
是行索引,而cn
是我要检查的列表单元格的列索引。 Given above, what iff my code checks any corner cell ? 上面给出了,如果我的代码检查任何角单元格,该怎么办? like say the first row and first column cell element with index
[0,0]
, some of the neighbours index will be negative. 例如说索引为
[0,0]
的第一行和第一列单元格元素,某些邻居索引将为负数。 My code has a special property that it prevents me to add additional rows or columns to the list indicated above. 我的代码有一个特殊的属性,它阻止我向上述列表中添加其他行或列。
How to deal with this ? 怎么处理呢? any help....
任何帮助...
to solve both the bound problem and the rr[i,j]
syntax, you can overload the getitem
method in a class: 要解决绑定问题和
rr[i,j]
语法,可以在类中重载getitem
方法:
class boundedlist(list):
def __getitem__(self,indices):
try:
l=list(self)
for i in indices : l=l[i]
return l
except IndexError:
return 0
Then all works like you want : 然后,所有工作如您所愿:
In [76]: brr=boundedlist(rr)
In [77]: brr[4,3]
Out[77]: 10
In [78]: brr[4,6]
Out[78]: 0
In [79]: brr[-1,6]
Out[79]: 0
In [80]: brr[10,4]
Out[80]: 0
You keep the row acces like that: 您可以像这样保留行访问权限:
In [81]: brr[[4]]
Out[81]: [10, 10, 10, 10, 10]
and you can generalize to more dimensions. 您可以将其推广到更多维度。 You will have to adapt
__setitem__
if you want to modify the data. 如果要修改数据,则必须修改
__setitem__
。
if you want to access cell(1,1)
in rr
list you have to use rr[1][1]
如果要访问
rr
列表中的cell(1,1)
,则必须使用rr[1][1]
for i in range(len(rr)):
for j in range(len(rr[i])):
if (i, j) in [(rn, cn+1), (rn-1,cn+1 ), (rn-1, cn ), (rn-1, cn-1 ), (rn, cn-1 ), (rn+1, cn-1 ), (rn+1, cn ), (rn+1, cn+1)]:
#Do some things
else:
#Do other things
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.