Python 中的循环数组索引

7
我正在寻找一个循环的数组(或矩阵),使得:
假设:
 a = [1,2,3]

那我想要。
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 1
a[4] = 2

对于a的所有索引值等同于“等等”。原因是我有一张图像作为矩阵,我想要处理它的行为是,如果它在一个方向上超出了边缘,它应该重新出现在相反的一侧。如果您有任何关于如何清晰地完成这个任务的建议,将不胜感激!

itertools 迭代 - sshashank124
等一下,它们是Python列表还是numpy数组? - thefourtheye
3个回答

11

你可以使用取模运算符,像这样

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数组的子类化更多信息可以在这里找到(感谢JonClements


OP想要一遍又一遍地循环。 - sshashank124
@sshashank124,请检查问题中的索引。 - thefourtheye

0

你可以非常简单地:

mainArr = [5,2,1,4,2]
def getRangeArray(startIndexInMainArray):
    s = mainArr[startIndexInMainArray::]
    b=len(mainArr)-len(s)
    return (s+mainArr[0:b])

print(mainArr)
print(getRangeArray(4)) # What is the first index?

#for index 4
#[5, 2, 1, 4, 2]  before
#[2, 5, 2, 1, 4]  after

#for index 2
#[5, 2, 1, 4, 2]  before
#[1, 4, 2, 5, 2]  after

#for index 0
#[5, 2, 1, 4, 2]  before
#[5, 2, 1, 4, 2]  after

0

拥有这样的功能对您的代码并不好。相反,编写一个生成器函数,为您生成轮换值。

numbers = [1, 2, 3]

def returnNumber():
    """
    A circular array for yielding list members repeatedly 
    """
    index = -1
    while True:
        index += 1
        yield slangWords[index % len(numbers)]

# Now you can use this generator
numberGenerator = returnNumber()
numberGenerator.next() # returns 1 
numberGenerator.next() # returns 2
numberGenerator.next() # returns 3
numberGenerator.next() # returns 1
numberGenerator.next() # returns 2

2
晚来的评论,但仍然要说。您真的应该说明为什么觉得拥有所说的功能不好。 - JS Lavertu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接