我希望得到一个圆形的数组(或矩阵),这样
让:
a = [1,2,3]
然后我想
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 1
a[4] = 2
等于a的所有索引值.
原因是因为我有一个图像作为矩阵,我正在尝试处理它的行为,如果它在一个方向上离开边缘,它应该重新出现在另一侧.
任何关于如何干净利落的提示将非常感谢!
解决方法:
您可以像这样使用模运算符
print a[3 % len(a)]
如果你不想像这样使用模运算符,你需要自己子类列表并实现__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]
产量
0 1
1 2
2 3
3 1
4 2
如果你想对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]
有关Subclassing Numpy Arrays的更多信息,请访问here(感谢JonClements)
标签:python,list