Pythonic Circular List

前端 未结 7 1924
闹比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:56

    If you want it as a class, I whipped up this quick CircularList:

    import operator
    
    class CircularList(list):
        def __getitem__(self, x):
            if isinstance(x, slice):
                return [self[x] for x in self._rangeify(x)]
    
            index = operator.index(x)
            try:
                return super().__getitem__(index % len(self))
            except ZeroDivisionError:
                raise IndexError('list index out of range')
    
        def _rangeify(self, slice):
            start, stop, step = slice.start, slice.stop, slice.step
            if start is None:
                start = 0
            if stop is None:
                stop = len(self)
            if step is None:
                step = 1
            return range(start, stop, step)
    

    It supports slicing, so

    CircularList(range(5))[1:10] == [1, 2, 3, 4, 0, 1, 2, 3, 4]
    

提交回复
热议问题