简体   繁体   中英

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

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)

where rn is the row index, and cn is the column index of the list cell that I wanted to inspect. 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. 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:

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.

if you want to access cell(1,1) in rr list you have to use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM