Use slice notation with collections.deque

前端 未结 6 2208
情话喂你
情话喂你 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

    This is an old question, but for any future travelers, the Python docs explicitly recommend using rotate for this:

    The rotate() method provides a way to implement deque slicing and deletion.

    https://docs.python.org/2/library/collections.html

    An implementation is relatively simple:

    def slice_deque(d, start, stop, step):
        d.rotate(-start)
        slice = list(itertools.islice(d, 0, stop-start, step))
        d.rotate(start)
        return slice
    

    Effectively the same as using islice directly, except that rotate is more efficient for skipping through to the starting point. On the other hand, it also temporarily modifies the deque, which could be a threadsafety concern.

提交回复
热议问题