Circular array indices in Python

前端 未结 2 1910
-上瘾入骨i
-上瘾入骨i 2021-01-14 12:05

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         


        
相关标签:
2条回答
  • 2021-01-14 12:24

    Having such functionality is not good for your code. Instead write a generator function which generates you round robin values.

    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
    
    0 讨论(0)
  • 2021-01-14 12:40

    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)

    0 讨论(0)
提交回复
热议问题