对集合使用切片表示法。deque
问题描述
如何高效、优雅、典雅地从以下deque
中提取项目3..6而不对其进行更改:
from collections import deque
q = deque('',maxlen=10)
for i in range(10,20):
q.append(i)
slice notation似乎不适用于deque
...
解决方案
import itertools
output = list(itertools.islice(q, 3, 7))
例如:
>>> 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]
这应该比到目前为止发布的其他解决方案更有效。证据?
[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
相关文章