python - 在 collections.deque 中使用切片表示法

标签 python slice deque

如何在不改变以下 deque 的情况下高效、优雅和 Python 地提取项目 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

关于python - 在 collections.deque 中使用切片表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7064289/

相关文章:

UITableViewCell唯一标识符?

algorithm - Tarjan 和 Mihaescu 的 "*simpler* real-time catenable deque"工作在哪里?

python - 如何使用存储在单独模块中的错误代码

python - 获取列表中的最大元组

python - 在 DataFrameGroupBy 对象的组内进行切片

arrays - 将字节保存到固定大小的字节数组缓冲区中的通用 Go 函数

qt - Qt 中等效的 std::deque 是什么?

python - 对 umount 进行融合操作

python click 应用程序失败并显示 "missing argument"但无法找到问题

javascript - 当未设置限制时,动态数组切片以限制长度