python - 如何在不弹出的情况下查看双端队列的前面?

标签 python collections deque

我想在决定是否弹出之前检查队列前端的条件。我如何使用 collections.deque 在 python 中实现这一点?

list(my_deque)[0]

看起来很丑而且性能很差。

最佳答案

TL;DR:假设您的 deque 被称为 d,只需检查 d[0],因为双端队列中的“最左边”元素是前面的(您可能想在双端队列的长度之前进行测试以确保它不为空)。采纳@ason​​gtoruin的建议,使用if d:来测试双端队列是否为空(等同于if len(d) == 0:,但更pythonic)

###为什么不转换成列表? 因为 deque 是可索引的并且您正在测试前端。虽然 deque 具有类似于列表的接口(interface),但其实现已针对前端和后端操作进行了优化。引用 documentation :

Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

如果您有很多操作访问队列的“中间”,则可能需要转换为列表。再次引用文档:

Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.

转换到 list 的复杂度为 O(n),但后续每次访问的复杂度为 O(1)。

关于python - 如何在不弹出的情况下查看双端队列的前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48640251/

相关文章:

python - 为什么 gif 动画中不使用完整的调色板?

c# - 检查 list<MyObject> 是否已经在集合中

java - 从 Set 中删除负值

python - 如何从 Python 的集合库中查看 deque 模块的源代码?

python - 如何从字符串或列表中读取配置?

python - 如何从模板获取字段数据并在添加到数据库之前使用它?

python - 将 groupby 转换为具有新列的单行

java - 将 Observable 添加到 Observable<Collection<Class>> 中

c++ - 为什么 push_back 或 push_front 使双端队列的迭代器无效?

c++ - 双端队列在C++中的实现