Circular array indices in Python

前端 未结 2 1912
-上瘾入骨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
    

提交回复
热议问题