Use slice notation with collections.deque

前端 未结 6 2238
情话喂你
情话喂你 2020-12-05 06:00

How would you extract items 3..6 efficiently, elegantly and pythonically from the following deque without altering it:

from collections import d         


        
6条回答
  •  庸人自扰
    2020-12-05 06:59

    you can override the __getitem__ method and create a SliceableDeque using islice.

    There are edge cases, you should consider (for example using negative slices doesn't work with islice).

    here is what I have been using:

    import itertools
    from collections import deque
    
    class SliceableDeque(deque):
        def __getitem__(self, s):
            try:
                start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
            except AttributeError:  # not a slice but an int
                return super().__getitem__(s)
            try:  # normal slicing
                return list(itertools.islice(self, start, stop, step))
            except ValueError:  # incase of a negative slice object
                length = len(self)
                start, stop = length + start if start < 0 else start, length + stop if stop < 0 else stop
                return list(itertools.islice(self, start, stop, step))
    

提交回复
热议问题