Python数据结构概览:除列表和元组外,还有哪些重要数据结构?
在Python中,除了列表(list)和元组(tuple),还有许多其他内置的数据结构,每种都有其独特的特性和用途。了解这些数据结构可以帮助你在不同的场景中选择最合适的一种,从而提高代码的效率和可读性。今天,就让我们一起探索Python中的其他常用数据结构。
一、字典(dict)
特点
示例
my_dict = {"name": "Alice", "age": 30, "role": "Developer"}
print(my_dict["name"]) # 输出:Alice
my_dict["age"] = 31
my_dict["city"] = "New York"
print(my_dict) # 输出:{'name': 'Alice', 'age': 31, 'role': 'Developer', 'city': 'New York'}
使用场景
二、集合(set)
特点
示例
my_set = {1, 2, 3, 4}
my_set.add(5)
my_set.remove(2)
print(my_set) # 输出:{1, 3, 4, 5}
使用场景
三、队列(queue.Queue)
特点
queue.Queue 是线程安全的,适合多线程环境。示例
from queue import Queue
my_queue = Queue()
my_queue.put(1)
my_queue.put(2)
print(my_queue.get()) # 输出:1
print(my_queue.get()) # 输出:2
使用场景
四、栈(list 或 collections.deque)
特点
示例
my_stack = []
my_stack.append(1)
my_stack.append(2)
print(my_stack.pop()) # 输出:2
print(my_stack.pop()) # 输出:1
或者使用 collections.deque:
from collections import deque
my_stack = deque()
my_stack.append(1)
my_stack.append(2)
print(my_stack.pop()) # 输出:2
print(my_stack.pop()) # 输出:1
使用场景
五、collections 模块中的高级数据结构
Python 的 collections 模块提供了许多高级数据结构,这些结构在某些场景下非常有用。
1. collections.Counter
from collections import Counter
my_list = [1, 2, 2, 3, 3, 3, 4]
counter = Counter(my_list)
print(counter) # 输出:Counter({3: 3, 2: 2, 1: 1, 4: 1})
2. collections.defaultdict
from collections import defaultdict
my_dict = defaultdict(int)
print(my_dict["key"]) # 输出:0
3. collections.OrderedDict
from collections import OrderedDict
my_dict = OrderedDict([("name", "Alice"), ("age", 30)])
print(my_dict) # 输出:OrderedDict([('name', 'Alice'), ('age', 30)])
4. collections.namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(11, y=22)
print(p.x) # 输出:11
print(p.y) # 输出:22
六、heapq 模块
特点
heapq 模块提供了堆队列算法,也称为优先队列。示例
import heapq
my_heap = []
heapq.heappush(my_heap, 3)
heapq.heappush(my_heap, 1)
heapq.heappush(my_heap, 2)
print(heapq.heappop(my_heap)) # 输出:1
print(heapq.heappop(my_heap)) # 输出:2
print(heapq.heappop(my_heap)) # 输出:3
使用场景
七、array 模块
特点
array 模块提供了高效的数组存储,适合存储大量同类型数据。示例
import array
my_array = array.array("i", [1, 2, 3, 4])
print(my_array[0]) # 输出:1
my_array.append(5)
print(my_array) # 输出:array('i', [1, 2, 3, 4, 5])
使用场景
八、bisect 模块
特点
bisect 模块提供了二分查找和插入的功能,适合有序列表。示例
import bisect
my_list = [1, 2, 4, 5]
bisect.insort(my_list, 3)
print(my_list) # 输出:[1, 2, 3, 4, 5]
使用场景
九、dataclasses 模块(Python 3.7+)
特点
dataclasses 模块提供了简化类定义的功能,适合存储数据的类。__init__、__repr__、__eq__等方法。示例
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(11, 22)
print(p) # 输出:Point(x=11, y=22)
使用场景
十、enum 模块(Python 3.4+)
特点
enum 模块提供了枚举类,适合定义一组固定的常量。示例
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # 输出:Color.RED
print(Color.RED.value) # 输出:1
使用场景
十一、types 模块
特点
types 模块提供了动态创建类型的功能,适合需要动态生成类或函数的场景。示例
import types
def create_class(name, bases, body):
return types.new_class(name, bases, {}, lambda ns: ns.update(body))
MyClass = create_class("MyClass", (object,), {"x": 10})
print(MyClass().x) # 输出:10
使用场景
十二、itertools 模块
特点
itertools 模块提供了许多用于处理迭代器的工具,适合处理复杂的迭代逻辑。示例
import itertools
# 无限序列
for i in itertools.count(10):
print(i)
if i > 20:
break
# 组合
for subset in itertools.combinations([1, 2, 3, 4], 2):
print(subset)
使用场景
十三、functools 模块
特点
functools 模块提供了许多用于处理函数的工具,适合需要对函数进行操作的场景。示例
import functools
@functools.lru_cache(maxsize=32)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(10)) # 输出:55
使用场景
十四、array 模块
特点
array 模块提供了高效的数组存储,适合存储大量同类型数据。示例
import array
my_array = array.array("i", [1, 2, 3, 4])
print(my_array[0]) # 输出:1
my_array.append(5)
print(my_array) # 输出:array('i', [1, 2, 3, 4, 5])
使用场景
十五、memoryview 对象
特点
memoryview 对象提供了一个可变的缓冲区接口,适合处理二进制数据。示例
import array
my_array = array.array("i", [1, 2, 3, 4])
my_memoryview = memoryview(my_array)
print(my_memoryview[0]) # 输出:1
my_memoryview[0] = 10
print(my_array) # 输出:array('i', [10, 2, 3, 4])
使用场景
十六、io 模块
牂点
io 模块提供了输入输出功能,适合处理文件、网络通信等。示例
import io
# 内存中的文件对象
my_file = io.StringIO("Hello, World!")
print(my_file.read()) # 输出:Hello, World!
my_file.write("Python is awesome!")
my_file.seek(0)
print(my_file.read()) # 输出:Hello, World!Python is awesome!
使用场景
十七、pathlib 模块
特点
pathlib 模块提供了路径操作功能,适合处理文件路径、目录等。示例
from pathlib import Path
# 获取当前路径
current_path = Path.cwd()
print(current_path) # 输出:当前路径
# 创建新文件
new_file = current_path / "new_file.txt"
new_file.touch()
print(new_file.exists()) # 输出:True
使用场景
十八、shelve 模块
特点
shelve 模块提供了持久化存储功能,适合存储键值对数据。示例
import shelve
# 打开数据库
with shelve.open("my_shelve") as db:
db["key"] = "value"
print(db["key"]) # 输出:value
使用场景
十九、sqlite3 模块
特点
sqlite3 模块提供了轻量级数据库功能,适合存储大规模数据。示例
import sqlite3
# 连接数据库
conn = sqlite3.connect("my_database.db")
cursor = conn.cursor()
# 创建表
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM users")
print(cursor.fetchall()) # 输出:[(1, 'Alice')]
# 关闭连接
conn.close()
使用场景
二十、json 模块
特点
json 模块提供了JSON操作功能,适合处理JSON数据。示例
import json
# 序列化
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
print(json_str) # 输出:{"name": "Alice", "age": 30}
# 反序列化
data = json.loads(json_str)
print(data) # 输出:{'name': 'Alice', 'age': 30}
使用场景
总结
Python提供了丰富多样的数据结构,每种都有其独特的特性和适用场景。除了列表和元组,还有字典、集合、队列、栈、collections模块中的高级数据结构、heapq模块、array模块、bisect模块、dataclasses模块、enum模块、types模块、itertools模块、functools模块、array模块、memoryview对象、io模块、pathlib模块、shelve模块、sqlite3模块、json模块等。
选择合适的数据结构可以让你的代码更加高效、安全且易于维护。希望这篇文章能帮助你在Python开发中更好地选择合适的数据结构!如果你还有其他问题或经验,欢迎在评论区留言,我们一起交流。
作者:黄豆匿zlib