Python中的循环数组索引

cjm*_*671 3 python list

我希望得到一个圆形的数组(或矩阵),这样

让:

 a = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

然后我想

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 1
a[4] = 2
Run Code Online (Sandbox Code Playgroud)

等于a的所有索引值.

原因是因为我有一个图像作为矩阵,我正在尝试处理它的行为,如果它在一个方向上离开边缘,它应该重新出现在另一侧.

任何关于如何干净利落的提示将非常感谢!

the*_*eye 8

您可以像这样使用模运算符

print a[3 % len(a)] 
Run Code Online (Sandbox Code Playgroud)

如果您不想使用这样的模运算符,则需要自己进行子类化list和实现__getitem__.

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]
Run Code Online (Sandbox Code Playgroud)

产量

0 1
1 2
2 3
3 1
4 2
Run Code Online (Sandbox Code Playgroud)

如果你想对Numpy Arrays做同样的事情,你可以这样做

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]
Run Code Online (Sandbox Code Playgroud)

有关Subclassing Numpy Arrays的更多信息,请访问此处(感谢JonClements)