我正在寻找一个圆形的数组(或矩阵),这样
让:
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)]
如果你不想像这样使用模运算符,你需要继承 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]
输出
0 1
1 2
2 3
3 1
4 2
如果你想对 Numpy 数组做同样的事情,你可以这样做
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]
可以找到有关子类化 Numpy 数组的更多信息 here (感谢JonClements)
关于python - Python 中的循环数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808141/