Pythonic Circular List

前端 未结 7 1941
闹比i
闹比i 2020-12-03 01:10

Say I have a list,

l = [1, 2, 3, 4, 5, 6, 7, 8]

I want to grab the index of an arbitrary element and the values of its neighbors. For examp

7条回答
  •  广开言路
    2020-12-03 01:53

    Using the modulo method that others have mentioned I have created a class with a property that implements a circular list.

    class Circle:
        """Creates a circular array of numbers
    
        >>> c = Circle(30)
        >>> c.position
        -1
        >>> c.position = 10
        >>> c.position
        10
        >>> c.position = 20
        >>> c.position
        20
        >>> c.position = 30
        >>> c.position
        0
        >>> c.position = -5
        >>> c.position
        25
        >>>
    
        """
        def __init__(self, size):
            if not isinstance(size, int):  # validating length
                raise TypeError("Only integers are allowed")
            self.size = size
    
        @property
        def position(self):
            try:
                return self._position
            except AttributeError:
                return -1
    
        @position.setter
        def position(self, value):
            positions = [x for x in range(0, self.size)]
            i = len(positions) - 1
            k = positions[(i + value + 1) % len(positions)]
            self._position = k
    

提交回复
热议问题