Use slice notation with collections.deque

2019-01-14 05:40发布

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

from collections import deque
q = deque('',maxlen=10)
for i in range(10,20):
    q.append(i)

the slice notation doesn't seem to work with deque...

4条回答
你好瞎i
2楼-- · 2019-01-14 05:53

I would prefer this, it's shorter so easier to read:

output = list(q)[3:6+1]
查看更多
Ridiculous、
3楼-- · 2019-01-14 05:54
import itertools
output = list(itertools.islice(q, 3, 7))

For example:

>>> import collections, itertools
>>> q = collections.deque(xrange(10, 20))
>>> q
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> list(itertools.islice(q, 3, 7))
[13, 14, 15, 16]

This should be more efficient the the other solutions posted so far. Proof?

[me@home]$ SETUP="import itertools,collections; q=collections.deque(xrange(1000000))"

[me@home]$ python -m timeit  "$SETUP" "list(itertools.islice(q, 10000, 20000))"
10 loops, best of 3: 68 msec per loop

[me@home]$ python -m timeit "$SETUP" "[q[i] for i in  xrange(10000, 20000)]"
10 loops, best of 3: 98.4 msec per loop

[me@home]$ python -m timeit "$SETUP" "list(q)[10000:20000]"
10 loops, best of 3: 107 msec per loop
查看更多
Rolldiameter
4楼-- · 2019-01-14 05:57

I'd add this as a new answer, to provide better formatting.

For simplicity, Shawn's answer is perfect, but if you often need to get a slice from dequeue, you might prefer to subclass it and add a __getslice__ method.

from collections import deque
from itertools import islice
class deque_slice(deque):
    def __new__(cls, *args):
        return deque.__new__(cls, *args)
    def __getslice__(self, start, end):
        return list(islice(self, start, end))

This won't support setting a new slice, but you can implement your own custom __setslice__ method using the same concept.

查看更多
\"骚年 ilove
5楼-- · 2019-01-14 06:13
output = [q[i] for i in range(3,6+1)]
查看更多
登录 后发表回答