Python 中常用的内置数据结构

1. 列表 (List)

列表是一种有序、可变的集合,可以存储任意类型的元素。使用方括号 [] 定义。

python 复制代码
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")  # 添加元素
print(fruits)  # 输出: ['apple', 'banana', 'cherry', 'orange']

2. 元组 (Tuple)

元组是一种有序、不可变的集合,可以存储任意类型的元素。使用小括号 () 定义。

python 复制代码
coordinates = (10, 20)
print(coordinates[0])  # 输出: 10

# 尽管元组本身是不可变的,但元组中的可变元素(如列表)仍然可以改变
nested_tuple = (1, [2, 3])
nested_tuple[1][0] = 4
print(nested_tuple)  # 输出: (1, [4, 3])

如果元组中只有一个元素那么需要在元素后面添加一个逗号。

python 复制代码
single_element_tuple = (42,)
print(type(single_element_tuple))  # 输出: <class 'tuple'>
print(single_element_tuple)        # 输出: (42,)

3. 字典 (Dictionary)

字典是一种无序的键值对集合,键必须是唯一的,值可以是任意类型。使用花括号 {} 定义。

python 复制代码
person = {"name": "Alice", "age": 30}
person["city"] = "New York"  # 添加键值对
print(person)  # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}

4. 集合 (Set)

集合是一种无序、不重复元素的集合。使用花括号 {}set() 函数定义。

python 复制代码
unique_numbers = {1, 2, 3, 4}
unique_numbers.add(5)  # 添加元素
print(unique_numbers)  # 输出: {1, 2, 3, 4, 5}

5. 字符串 (String)

字符串是字符的有序集合,用单引号 ' 或双引号 " 定义。字符串是不可变的。

python 复制代码
message = "Hello, World!"
print(message.upper())  # 输出: 'HELLO, WORLD!'

6. 队列 (Queue)

队列是一种先进先出 (FIFO) 的数据结构。可以使用 collections.deque 模块来实现队列。

python 复制代码
from collections import deque

queue = deque(["Alice", "Bob", "Charlie"])
queue.append("Dave")  # 添加元素到队列末尾
print(queue.popleft())  # 输出: 'Alice' 并移除

7. 堆栈 (Stack)

堆栈是一种后进先出 (LIFO) 的数据结构。列表可以用作堆栈。

python 复制代码
stack = [1, 2, 3]
stack.append(4)  # 添加元素到堆栈顶部
print(stack.pop())  # 输出: 4 并移除

8. 队列 (Priority Queue)

优先队列可以使用 heapq 模块实现,它允许以元素的优先级顺序来访问元素。

python 复制代码
import heapq

heap = [1, 3, 5, 7]
heapq.heappush(heap, 2)  # 添加元素并保持堆的属性
print(heapq.heappop(heap))  # 输出: 1 并移除

9. 有序字典 (OrderedDict)

OrderedDict 是一种记住插入顺序的字典,使用 collections 模块。

python 复制代码
from collections import OrderedDict

ordered_dict = OrderedDict()
ordered_dict["one"] = 1
ordered_dict["two"] = 2
print(ordered_dict)  # 输出: OrderedDict([('one', 1), ('two', 2)])

10. 默认字典 (defaultdict)

defaultdict 是一种带有默认值的字典,使用 collections 模块。

python 复制代码
from collections import defaultdict

default_dict = defaultdict(int)
default_dict["count"] += 1
print(default_dict)  # 输出: defaultdict(<class 'int'>, {'count': 1})

总结

这些内置数据结构在处理不同类型的数据时非常有用。选择合适的数据结构可以提高代码的效率和可读性。理解和善用这些数据结构是高效编程的重要一环。

相关推荐
勤奋的凯尔森同学36 分钟前
webmin配置终端显示样式,模仿UbuntuDesktop终端
linux·运维·服务器·ubuntu·webmin
Hylan_J1 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶1 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
丁卯4041 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
chengooooooo2 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
人间打气筒(Ada)3 小时前
MySQL主从架构
服务器·数据库·mysql
失败尽常态5234 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
落笔画忧愁e4 小时前
FastGPT快速将消息发送至飞书
服务器·数据库·飞书
2501_904447744 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农4 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx