Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular array indices in Python

Tags:

python

list

I'm looking to get an array (or matrix) that is circular, such that

Let:

 a = [1,2,3]

Then I would like

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 1
a[4] = 2

Etc for all index values of a.

The reason is because I have an image as a matrix and what I'm trying to process it with the behaviour that if it goes off the edge in one direction, it should reappear on the opposite side.

Any tips on how to do this cleanly would be much appreciated!

like image 660
cjm2671 Avatar asked Feb 13 '23 08:02

cjm2671


1 Answers

You can use modulo operator, like this

print a[3 % len(a)] 

If you don't want to use modulo operator like this, you need to subclass list and implement __getitem__, yourself.

class CustomList(list):
    def __getitem__(self, index):
        return super(CustomList, self).__getitem__(index % len(self))

a = CustomList([1, 2, 3])
for index in xrange(5):
    print index, a[index]

Output

0 1
1 2
2 3
3 1
4 2

If you want to do the same with Numpy Arrays, you can do like this

import numpy as np

class CustomArray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        return np.asarray(args[0]).view(cls)

    def __getitem__(self, index):
        return np.ndarray.__getitem__(self, index % len(self))

a = CustomArray([1, 2, 3])
for index in xrange(5):
    print a[index]

More information about Subclassing Numpy Arrays can be found here (Thanks to JonClements)

like image 101
thefourtheye Avatar answered Feb 16 '23 02:02

thefourtheye