Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python deque

作者:朕不想活了   发布日期:2025-06-14   浏览:17

from collections import deque

# 创建一个空的双端队列
d = deque()

# 添加元素到队列的右侧
d.append('a')
d.append('b')
print(d)  # 输出: deque(['a', 'b'])

# 添加元素到队列的左侧
d.appendleft('c')
print(d)  # 输出: deque(['c', 'a', 'b'])

# 从右侧移除并返回一个元素
right_element = d.pop()
print(right_element)  # 输出: b
print(d)  # 输出: deque(['c', 'a'])

# 从左侧移除并返回一个元素
left_element = d.popleft()
print(left_element)  # 输出: c
print(d)  # 输出: deque(['a'])

# 设置最大长度,当超过时会自动从对侧移除元素
d_with_maxlen = deque(maxlen=3)
d_with_maxlen.append(1)
d_with_maxlen.append(2)
d_with_maxlen.append(3)
print(d_with_maxlen)  # 输出: deque([1, 2, 3], maxlen=3)

d_with_maxlen.append(4)
print(d_with_maxlen)  # 输出: deque([2, 3, 4], maxlen=3)

# 扩展队列
d.extend(['d', 'e'])
print(d)  # 输出: deque(['a', 'd', 'e'])

# 从左侧扩展队列
d.extendleft(['f', 'g'])
print(d)  # 输出: deque(['g', 'f', 'a', 'd', 'e'])

# 旋转队列
d.rotate(2)
print(d)  # 输出: deque(['d', 'e', 'g', 'f', 'a'])

# 逆向旋转队列
d.rotate(-2)
print(d)  # 输出: deque(['g', 'f', 'a', 'd', 'e'])

解释说明:

  • deque 是 Python 标准库 collections 模块中的一个类,表示双端队列(double-ended queue),可以从两端高效地添加或移除元素。
  • append()appendleft() 分别用于在队列的右侧和左侧添加元素。
  • pop()popleft() 分别用于从队列的右侧和左侧移除并返回一个元素。
  • maxlen 参数可以设置队列的最大长度,当超过时会自动从对侧移除元素。
  • extend()extendleft() 分别用于从右侧和左侧扩展队列。
  • rotate() 方法用于旋转队列,正数表示向右旋转,负数表示向左旋转。

上一篇:lambda在python中的用法

下一篇:python脚本怎么写

大家都在看

python时间格式

python ord和chr

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

python中list代表什么

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站