国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Start using Deque
Efficiently popping and appending elements
訪問(wèn)Deque中的任意元素
用Deque構(gòu)建高效隊(duì)列
總結(jié)
Home Backend Development Python Tutorial Deque in Python: Implementing efficient queues and stacks

Deque in Python: Implementing efficient queues and stacks

Apr 12, 2023 pm 09:46 PM
python heap queue

Deque in Python is a low-level, highly optimized double-ended queue, useful for implementing elegant and efficient Pythonic queues and stacks, which are the most common list-based data types in computing.

In this article, Mr. Yun Duo will learn the following together with you:

  • Start using deque
  • Effectively pop up and append elements
  • Access deque Any element in
  • Use deque to build an efficient queue

Start using Deque

The operation of appending elements to the right end of the Python list and popping elements is generally very efficient. If time complexity is expressed in Big O, then we can say that they are O(1). When Python needs to reallocate memory to increase the underlying list to accept new elements, these operations will slow down and the time complexity may become O(n).

In addition, the operations of appending and popping elements to the left end of the Python list are also very inefficient, with a time complexity of O(n).

Since lists provide .append() and .pop() operations, they can be used as stacks and queues. The performance issues of appending and popping operations on the left and right ends of the list will greatly affect the overall performance of the application.

Python’s deque was the first data type added to the collections module as early as Python 2.4. This data type is specifically designed to overcome the efficiency issues of .append() and .pop() in Python lists.

Deques are sequence-like data types designed as a generalization of stacks and queues. They support memory-efficient and fast append and pop operations on both ends of the data structure.

Append and pop operations on both ends of a deque object are stable and equally efficient because the deque is implemented as a doubly linked list. Additionally, append and pop operations on deque are also thread-safe and memory-efficient. These features make deque particularly useful for creating custom stacks and queues in Python.

If you need to save the last seen element list, you can also use deque, because the maximum length of deque can be limited. If we do this, then once the deque is full, it will automatically discard the elements at one end when we add new elements at the other end.

The following is a summary of the main features of deque:

  • Stores elements of any data type
  • Is a variable data type
  • Supports in The member operations of the operator
  • support indexing, such as a_deque[i]
  • does not support slicing, such as a_deque[0:2]
  • supports sequences and iterable objects. Built-in functions for operations, such as len(), sorted(), reversed(), etc.
  • Does not support inplace sorting
  • Supports normal iteration and reverse iteration
  • Supports the use of pickle
  • Ensure fast, memory efficient, and thread-safe pop and append operations on both ends

Creating a deque instance is relatively simple. Just import deque from the collection and call it with an optional iterator as argument.

>>> from collections import deque

>>> # 創(chuàng)建一個(gè)空的 deque
>>> deque()
deque([])

>>> # 使用不同的迭代器來(lái)創(chuàng)建 deque
>>> deque((1, 2, 3, 4))
deque([1, 2, 3, 4])

>>> deque([1, 2, 3, 4])
deque([1, 2, 3, 4])

>>> deque(range(1, 5))
deque([1, 2, 3, 4])

>>> deque("abcd")
deque(['a', 'b', 'c', 'd'])

>>> numbers = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> deque(numbers.keys())
deque(['one', 'two', 'three', 'four'])

>>> deque(numbers.values())
deque([1, 2, 3, 4])

>>> deque(numbers.items())
deque([('one', 1), ('two', 2), ('three', 3), ('four', 4)])

If you instantiate deque without providing iterable as a parameter, you will get an empty deque. If an iterable is provided and entered, the deque initializes a new instance with its data. Initialization proceeds from left to right using deque.append().

Deque initializer requires the following two optional parameters.

  • iterable An iterator that provides initialization data.
  • maxlen is an integer specifying the maximum length of deque.

As mentioned before, if you don't provide an iterable, then you will get an empty deque. If you provide a value for maxlen, then your deque will only store the items up to maxlen.

Finally, you can also use unordered iterable objects, such as collections, to initialize deque. In these cases, there will be no predefined order of elements in the final deque.

Efficiently popping and appending elements

The most important difference between Deque and List is that the former can perform efficient appending and popping operations at both ends of the sequence. The Deque class implements specialized .popleft() and .appendleft() methods to directly operate on the left end of the sequence.

>>> from collections import deque

>>> numbers = deque([1, 2, 3, 4])
>>> numbers.popleft()
1
>>> numbers.popleft()
2
>>> numbers
deque([3, 4])

>>> numbers.appendleft(2)
>>> numbers.appendleft(1)
>>> numbers
deque([1, 2, 3, 4])

Here, use .popleft() and .appendleft() to pop up and increase the left end value of numbers respectively. These methods are designed for deque, and list has no such method.

Deque also provides .append() and .pop() methods like list to operate on the right end of the sequence. However, the behavior of .pop() is different.

>>> from collections import deque

>>> numbers = deque([1, 2, 3, 4])
>>> numbers.pop()
4

>>> numbers.pop(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no arguments (1 given)

Here, .pop() removes and returns the last element in the deque container. This method does not accept an index as a parameter, so it cannot be used to remove arbitrary items from the deque. You can only use it to remove and return the rightmost item.

We think deque is a doubly linked list. Therefore, each item in a given deque container holds a reference (pointer) to the previous and next item in the sequence.

Double linked lists make the operation of adding and popping elements from both ends simple and efficient, because only the pointers need to be updated, therefore, the two operations have similar performance, both are O(1). They are also predictable in terms of performance because there is no need to reallocate memory and move existing items to accept new items.

從常規(guī) Python 列表的左端追加和彈出元素需要移動(dòng)所有元素,這最終是一個(gè) O(n) 操作。此外,將元素添加到列表的右端通常需要Python重新分配內(nèi)存,并將當(dāng)前項(xiàng)復(fù)制到新的內(nèi)存位置,之后,它可以添加新項(xiàng)。這個(gè)過(guò)程需要更長(zhǎng)的時(shí)間來(lái)完成,并且追加操作從 O(1)傳遞到 O(n)。

考慮以下關(guān)于在序列左端添加項(xiàng)的性能測(cè)試,deque vs list。

# time_append.py

from collections import deque
from time import perf_counter

TIMES = 10_000
a_list = []
a_deque = deque()

def average_time(func, times):
total = 0.0
for i in range(times):
start = perf_counter()
func(i)
total += (perf_counter() - start) * 1e9
return total / times

list_time = average_time(lambda i: a_list.insert(0, i), TIMES)
deque_time = average_time(lambda i: a_deque.appendleft(i), TIMES)
gain = list_time / deque_time

print(f"list.insert(){list_time:.6} ns")
print(f"deque.appendleft() {deque_time:.6} ns({gain:.6}x faster)")

在這個(gè)腳本中,average_time() 計(jì)算了執(zhí)行一個(gè)給定次數(shù)的函數(shù)(func)的平均時(shí)間。如果我們?cè)诿钚兄羞\(yùn)行該腳本,那么我們會(huì)得到以下輸出。

$ python time_append.py
list.insert()3735.08 ns
deque.appendleft() 238.889 ns(15.6352x faster)

在這個(gè)例子中,deque 上的 .appendleft() 要比 list 上的 .insert() 快幾倍。注意 deque.appendleft() 執(zhí)行時(shí)間是常量O(1)。但列表左端的 list.insert() 執(zhí)行時(shí)間取決于要處理的項(xiàng)的數(shù)量O(n)。

在這個(gè)例子中,如果增加 TIMES 的值,那么 list.insert() 會(huì)有更高的時(shí)間測(cè)量值,而 deque.appendleft() 會(huì)得到穩(wěn)定(常數(shù))的結(jié)果。如果對(duì) deque 和 list 的 pop 操作進(jìn)行類(lèi)似的性能測(cè)試,那么可以展開(kāi)下面的練習(xí)塊。

Exercise:測(cè)試 deque.popleft() 與 list.pop(0) 的性能

可以將上面的腳本修改為時(shí)間deque.popleft()與list.pop(0)操作并估計(jì)它們的性能。

Solution:測(cè)試 deque.popleft() 與 list.pop(0) 的性能

# time_pop.py

from collections import deque
from time import perf_counter

TIMES = 10_000
a_list = [1] * TIMES
a_deque = deque(a_list)

def average_time(func, times):
total = 0.0
for _ in range(times):
start = perf_counter()
func()
total += (perf_counter() - start) * 1e9
return total / times

list_time = average_time(lambda: a_list.pop(0), TIMES)
deque_time = average_time(lambda: a_deque.popleft(), TIMES)
gain = list_time / deque_time

print(f"list.pop(0) {list_time:.6} ns")
print(f"deque.popleft() {deque_time:.6} ns({gain:.6}x faster)")
list.pop(0) 2002.08 ns
deque.popleft() 326.454 ns(6.13282x faster)

同樣,它deque比list從底層序列的左端刪除元素要快。
嘗試更改TIMES的值,看看會(huì)發(fā)生什么

Deque 數(shù)據(jù)類(lèi)型的設(shè)計(jì)是為了保證在序列的兩端進(jìn)行有效的追加和彈出操作。它是處理需要在 Python 中實(shí)現(xiàn)隊(duì)列和堆棧數(shù)據(jù)結(jié)構(gòu)的問(wèn)題的理想選擇。

訪問(wèn)Deque中的任意元素

Python 的 deque 返回可變的序列,其工作方式與列表相當(dāng)類(lèi)似。除了可以有效地從其末端追加和彈出元素外,deque 還提供了一組類(lèi)似列表的方法和其他類(lèi)似序列的操作,以處理任意位置的元素。下面是其中的一些。

選項(xiàng)

描述

.insert(i, value)

在索引為i的deque容器中插入一個(gè)名為value的元素。

.remove (value)

刪除第一個(gè)出現(xiàn)的 value ,如果 value 不存在則引發(fā)ValueError

a_deque[i]

從一個(gè)deque容器中檢索索引為 i 的項(xiàng)。

del a_deque[i]

Removes the item with index i from the deque container.

我們可以使用這些方法和技術(shù)來(lái)處理 deque 對(duì)象內(nèi)部任何位置的元素。下面是如何做到這一點(diǎn)的。

>>> from collections import deque
>>> letters = deque("abde")
>>> letters.insert(2, "c")
>>> letters
deque(['a', 'b', 'c', 'd', 'e'])

>>> letters.remove("d")
>>> letters
deque(['a', 'b', 'c', 'e'])

>>> letters[1]
'b'

>>> del letters[2]
>>> letters
deque(['a', 'b', 'e'])

在這里,首先將"c"插入到位置 2的letters中。然后使用 .remove() 從deque容器中移除"d"。Deque 還允許索引來(lái)訪問(wèn)元素,在這里使用它來(lái)訪問(wèn)索引1處的b。最后,你可以使用 del 關(guān)鍵字從 deque 中刪除任何存在的項(xiàng)。請(qǐng)注意, .remove() 允許按值刪除項(xiàng),而del則按索引刪除項(xiàng)。

盡管 deque 對(duì)象支持索引,但它們不支持切片,即不能像常規(guī)列表一樣使用切片語(yǔ)法, [start:stop:step] 從現(xiàn)有的 deque 中提?。?/p>

>>> from collections import deque
>>> numbers = deque([1, 2, 3, 4, 5])
>>> numbers[1:3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'

Deque支持索引,卻不支持分片。通常來(lái)說(shuō)在一個(gè)鏈表上執(zhí)行切片非常低效。

雖然 deque 與 list 非常相似,但 list 是基于數(shù)組的,而 deque 是基于雙鏈表的。

Deque 基于雙鏈表,在訪問(wèn)、插入和刪除任意元素都是無(wú)效操作。如果需要執(zhí)行這些操作,則解釋器必須在deque中進(jìn)行迭代,直到找到想要的元素。因而他們的時(shí)間復(fù)雜度是O(n)而不是O(1)。

下面演示了在處理任意元素時(shí) deques 和 list 的行為。

# time_random_access.py

from collections import deque
from time import perf_counter

TIMES = 10_000
a_list = [1] * TIMES
a_deque = deque(a_list)

def average_time(func, times):
total = 0.0
for _ in range(times):
start = perf_counter()
func()
total += (perf_counter() - start) * 1e6
return total / times

def time_it(sequence):
middle = len(sequence) // 2
sequence.insert(middle, "middle")
sequence[middle]
sequence.remove("middle")
del sequence[middle]

list_time = average_time(lambda: time_it(a_list), TIMES)
deque_time = average_time(lambda: time_it(a_deque), TIMES)
gain = deque_time / list_time

print(f"list{list_time:.6} μs ({gain:.6}x faster)")
print(f"deque {deque_time:.6} μs")

這個(gè)腳本對(duì)插入、刪除和訪問(wèn)一個(gè) deque 和一個(gè) list 中間的元素進(jìn)行計(jì)時(shí)。如果運(yùn)行這個(gè)腳本,得到如下所示的輸出:

$ python time_random_access.py
list63.8658 μs (1.44517x faster)
deque 92.2968 μs

Deque并不像列表那樣是隨機(jī)訪問(wèn)的數(shù)據(jù)結(jié)構(gòu)。因此,從 deque 的中間訪問(wèn)元素的效率要比在列表上做同樣的事情低。這說(shuō)明 deque 并不總是比列表更有效率。

Python 的 deque 對(duì)序列兩端的操作進(jìn)行了優(yōu)化,所以它們?cè)谶@方面一直比 list 好。另一方面,列表更適合于隨機(jī)訪問(wèn)和固定長(zhǎng)度的操作。下面是 deque 和 list 在性能上的一些區(qū)別。

對(duì)于列表,當(dāng)解釋器需要擴(kuò)大列表以接受新項(xiàng)時(shí),.append()的性能優(yōu)勢(shì)受到內(nèi)存重新分配的影響而被降低。此操作需要將所有當(dāng)前項(xiàng)復(fù)制到新的內(nèi)存位置,這將極大地影響性能。

此總結(jié)可以幫助我們?yōu)槭诸^的問(wèn)題選擇適當(dāng)?shù)臄?shù)據(jù)類(lèi)型。但是,在從列表切換到 deque 之前,一定要對(duì)代碼進(jìn)行剖析,它們都有各自的性能優(yōu)勢(shì)。

用Deque構(gòu)建高效隊(duì)列

Deque 是一個(gè)雙端隊(duì)列,提供了堆棧和隊(duì)列的泛化。在本節(jié)中,我們將一起學(xué)習(xí)如何使用deque以?xún)?yōu)雅、高效和Pythonic的方式在底層實(shí)現(xiàn)我們自己的隊(duì)列抽象數(shù)據(jù)類(lèi)型(ADT)。

注意: 在 Python 標(biāo)準(zhǔn)庫(kù)中,queue 模塊實(shí)現(xiàn)了多生產(chǎn)者、多消費(fèi)者的隊(duì)列,可以在多個(gè)線程之間安全地交換信息。

如果你正在處理隊(duì)列,那么最好使用那些高級(jí)抽象而不是 deque ,除非你正在實(shí)現(xiàn)自己的數(shù)據(jù)結(jié)構(gòu)。

隊(duì)列是元素的collections,可以通過(guò)在一端添加元素和從另一端刪除元素來(lái)修改隊(duì)列。

隊(duì)列 以先入先出(FIFO)的方式管理元素,像一個(gè)管道一樣工作,在管道的一端推入新元素,并從另一端彈出舊元素。向隊(duì)列的一端添加一個(gè)元素稱(chēng)為 enqueue 操作;從另一端刪除一個(gè)元素稱(chēng)為 dequeue。

為了更好地理解隊(duì)列,以餐廳為例,餐館里有很多人在排隊(duì)等著點(diǎn)餐。通常情況下,后來(lái)的人將排在隊(duì)列的末端。一旦有了空桌子,排在隊(duì)伍開(kāi)頭的人就會(huì)離開(kāi)隊(duì)伍進(jìn)去用餐。

下面演示了使用一個(gè)原始的deque對(duì)象來(lái)模擬這個(gè)過(guò)程。

>>> from collections import deque

>>> customers = deque()

>>> # People arriving
>>> customers.append("Jane")
>>> customers.append("John")
>>> customers.append("Linda")

>>> customers
deque(['Jane', 'John', 'Linda'])

>>> # People getting tables
>>> customers.popleft()
'Jane'
>>> customers.popleft()
'John'
>>> customers.popleft()
'Linda'

>>> # No people in the queue
>>> customers.popleft()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from an empty deque

首先創(chuàng)建一個(gè)空的 deque 對(duì)象來(lái)表示到達(dá)餐廳的人的隊(duì)列。person排隊(duì)放入隊(duì)列,可以使用.append(),將單個(gè)條目添加到右端。要從隊(duì)列中取出一個(gè)person,可以使用.popleft() ,刪除并返回deque容器左側(cè)的各個(gè)條目。

用隊(duì)列模擬工作,然而,由于deque是一個(gè)泛化,它的API]不匹配常規(guī)的隊(duì)列API。例如,不是.enqueue(),而是.append()。還有.popleft() 而不是.dequeue()。此外,deque 還提供了其他一些可能不符合特定需求的操作。

我們可以創(chuàng)建具有特定功能的自定義隊(duì)列類(lèi)??梢栽趦?nèi)部使用 deque 來(lái)存儲(chǔ)數(shù)據(jù),并在自定義隊(duì)列中提供所需的功能。我們可以把它看作是適配器設(shè)計(jì)模式的一個(gè)實(shí)現(xiàn),在這個(gè)模式中,把 deque 的接口轉(zhuǎn)換成看起來(lái)更像隊(duì)列接口的東西。

例如,需要一個(gè)自定義的隊(duì)列抽象數(shù)據(jù)類(lèi)型,提供以下功能。

  • 排列元素
  • 去排隊(duì)的元素
  • 返回隊(duì)列的長(zhǎng)度
  • 支持成員資格測(cè)試
  • 支持正常和反向迭代
  • 提供一個(gè)方便用戶(hù)的字符串表示法

此時(shí)可以寫(xiě)一個(gè)Queue類(lèi)。

# custom_queue.py

from collections import deque

class Queue:
def __init__(self):
self._items = deque()

def enqueue(self, item):
self._items.append(item)

def dequeue(self):
try:
return self._items.popleft()
except IndexError:
raise IndexError("dequeue from an empty queue") from None

def __len__(self):
return len(self._items)

def __contains__(self, item):
return item in self._items

def __iter__(self):
yield from self._items

def __reversed__(self):
yield from reversed(self._items)

def __repr__(self):
return f"Queue({list(self._items)})"

._items 是一個(gè) deque 對(duì)象,可以存儲(chǔ)和操作隊(duì)列中的元素。Queue使用 deque.append() 實(shí)現(xiàn)了 .enqueue(),將元素添加到隊(duì)列的末端。還用 deque.popleft() 實(shí)現(xiàn)了 .dequeue(),以有效地從隊(duì)列的開(kāi)頭刪除元素。

支持以下特殊方法

運(yùn)作

??deque??

??list??

通過(guò)索引訪問(wèn)任意的元素

O(n)

O(1)

在左端彈出和追加元素

O(1)

O(n)

Pop and append elements at the right end

O (1)

##O(1) Redistribute

Insert and delete elements in the middle

O(n)

O(n)

理想情況下,.__repr__()返回一個(gè)字符串,代表一個(gè)有效的 Python 表達(dá)式??梢杂眠@個(gè)表達(dá)式以相同的值重新創(chuàng)建這個(gè)對(duì)象。

然而,在上面的例子中,目的是使用方法的返回值在 interactive shell 上優(yōu)雅地顯示對(duì)象??梢酝ㄟ^(guò)接受初始化可迭代對(duì)象作為.__init__() 的參數(shù)并從中構(gòu)建實(shí)例,從而從這個(gè)特定的字符串表示形式構(gòu)建 Queue 實(shí)例。

有了這些補(bǔ)充,Queue 類(lèi)就完成了。要在我們的代碼中使用這個(gè)類(lèi),我們可以做如下事情。

>>> from custom_queue import Queue
>>> numbers = Queue()
>>> numbers
Queue([])

>>> # Enqueue items
>>> for number in range(1, 5):
... numbers.enqueue(number)
...
>>> numbers
Queue([1, 2, 3, 4])

>>> # Support len()
>>> len(numbers)
4

>>> # Support membership tests
>>> 2 in numbers
True
>>> 10 in numbers
False

>>> # Normal iteration
>>> for number in numbers:
... print(f"Number: {number}")
...
1
2
3
4

總結(jié)

隊(duì)列和堆棧是編程中常用的?抽象數(shù)據(jù)類(lèi)型。它們通常需要在底層數(shù)據(jù)結(jié)構(gòu)的兩端進(jìn)行有效的?pop?和?append?操作。Python 的 collections 模塊提供了一種叫做 deque 的數(shù)據(jù)類(lèi)型,它是專(zhuān)門(mén)為兩端的快速和節(jié)省內(nèi)存的追加和彈出操作而設(shè)計(jì)的。

有了deque,我們可以用優(yōu)雅、高效和Pythonic的方式在低層次上編寫(xiě)我們自己的隊(duì)列和堆棧。

總結(jié)下本文所學(xué)內(nèi)容:

  • 如何在代碼中創(chuàng)建和使用Python的deque
  • 如何有效地從deque的兩端追加和彈出項(xiàng)目
  • 如何使用deque來(lái)構(gòu)建高效的隊(duì)列和堆棧
  • 什么時(shí)候值得使用deque而不是list

The above is the detailed content of Deque in Python: Implementing efficient queues and stacks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

How to test an API with Python How to test an API with Python Jul 12, 2025 am 02:47 AM

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

Python variable scope in functions Python variable scope in functions Jul 12, 2025 am 02:49 AM

In Python, variables defined inside a function are local variables and are only valid within the function; externally defined are global variables that can be read anywhere. 1. Local variables are destroyed as the function is executed; 2. The function can access global variables but cannot be modified directly, so the global keyword is required; 3. If you want to modify outer function variables in nested functions, you need to use the nonlocal keyword; 4. Variables with the same name do not affect each other in different scopes; 5. Global must be declared when modifying global variables, otherwise UnboundLocalError error will be raised. Understanding these rules helps avoid bugs and write more reliable functions.

Python FastAPI tutorial Python FastAPI tutorial Jul 12, 2025 am 02:42 AM

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

Python for loop with timeout Python for loop with timeout Jul 12, 2025 am 02:17 AM

Add timeout control to Python's for loop. 1. You can record the start time with the time module, and judge whether it is timed out in each iteration and use break to jump out of the loop; 2. For polling class tasks, you can use the while loop to match time judgment, and add sleep to avoid CPU fullness; 3. Advanced methods can consider threading or signal to achieve more precise control, but the complexity is high, and it is not recommended for beginners to choose; summary key points: manual time judgment is the basic solution, while is more suitable for time-limited waiting class tasks, sleep is indispensable, and advanced methods are suitable for specific scenarios.

How to parse large JSON files in Python? How to parse large JSON files in Python? Jul 13, 2025 am 01:46 AM

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

Python for loop over a tuple Python for loop over a tuple Jul 13, 2025 am 02:55 AM

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

What are python default arguments and their potential issues? What are python default arguments and their potential issues? Jul 12, 2025 am 02:39 AM

Python default parameters are evaluated and fixed values ??when the function is defined, which can cause unexpected problems. Using variable objects such as lists as default parameters will retain modifications, and it is recommended to use None instead; the default parameter scope is the environment variable when defined, and subsequent variable changes will not affect their value; avoid relying on default parameters to save state, and class encapsulation state should be used to ensure function consistency.

See all articles

      Method

      Support

      ??.__len__ ()??

      length of ??len()??

      ##?

      ?.__contains__( )??

      Member test with?

      ?in??

      ?

      ?.__iter__()??

      Regular iteration

      ?

      ?.__reversed__()??

      Reverse iteration

      ?

      ? .__repr__()??

      String representation