Python教程今天介绍双向队列。
虽然可以使用 Python 列表的 .append 和 .pop 方法模拟栈或者队列,但删除列表的第一个元素或者在第一个元素之前添加一个新元素,都非常耗时。因为需要把列表中的所有元素向后移动。
Python 的双向队列使用 collections.deque 类来实现。它是一个线程安全且可以快速从两端添加或者删除元素的类。
deque /dɛk/
也可以利用 collections.deque 类来实现缓存。首先先指定缓存队列的大小,然后从队首删除过期元素和在队尾添加新元素。
Luciano Ramalho 举了一个示例来说明双向队列的基本用法。
from collections import deque dq = deque(range(10), maxlen=10) logging.info('dq -> %s', dq) dq.rotate(3) logging.info('dq -> %s', dq) dq.rotate(-4) logging.info('dq -> %s', dq) dq.extend([11, 22, 33]) logging.info('dq -> %s', dq) dq.extendleft([10, 20, 30, 40]) logging.info('dq -> %s', dq)复制代码
运行结果:
INFO - dq -> deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10) INFO - dq -> deque([7, 8, 9, 0, 1, 2, 3, 4, 5, 6], maxlen=10) INFO - dq -> deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], maxlen=10) INFO - dq -> deque([4, 5, 6, 7, 8, 9, 0, 11, 22, 33], maxlen=10) INFO - dq -> deque([40, 30, 20, 10, 4, 5, 6, 7, 8, 9], maxlen=10)复制代码
- maxlen 是 deque 的可选参数,用于指定队列容量,即可以放多少个元素。
- rotate() 方法可以旋转队列。它有一个入参 n ,当 n >0时,队列从最右边开始的 n 个元素会被移动到左边。当 n
- extend() 方法可以为队列添加新元素,它接受一个列表作为入参,会把列表中的所有元素添加到队列中。新的元素放置在队列右边。
- 如果在添加新元素时发现队列已满,这时就会自动删除队首的元素。
- extendleft(iter) 方法是把新增的元素放置在队列左边。其它特性与 extend() 方法相同。
双向队列也不是完美的,如果从队列中间位置删除元素就比较慢,因为它只针对队列的头尾操作做了优化。
相关免费学习推荐:python教程(视频)
The above is the detailed content of Let's talk about Python's two-way queue. For more information, please follow other related articles on the PHP Chinese website!

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
