Python 数据结构
Python 提供了多种数据结构来存储和操作数据,其中列表(list)、字典(dict)、元组(tuple)和集合(set)是最常用的几种。本章将详细介绍这些数据结构的基本操作及其应用。
1.2.1 列表(list)
列表(list)是 Python 中最常见的数据结构之一,它是一个有序 、可变的序列,可以存储不同类型的元素。
1. 创建列表
python
# 创建一个包含多个元素的列表
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True] # 可以存储不同类型的元素
empty_list = [] # 创建空列表
2. 索引和切片
python
# 访问列表元素(索引从 0 开始)
print(numbers[0]) # 输出 1
print(numbers[-1]) # 输出 5(负索引表示从后往前)
# 切片操作(获取子列表)
print(numbers[1:4]) # 输出 [2, 3, 4]
print(numbers[:3]) # 输出 [1, 2, 3]
print(numbers[::2]) # 输出 [1, 3, 5](步长为 2)
3. 遍历列表
python
# 使用 for 循环遍历列表
for num in numbers:
print(num)
# 使用 enumerate() 获取索引和值
for index, value in enumerate(numbers):
print(f"索引 {index} 对应的值是 {value}")
4. 列表推导式
列表推导式是一种简洁的方式来创建列表。
python
# 生成 0-9 的平方列表
squares = [x**2 for x in range(10)]
print(squares) # 输出 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 生成偶数列表
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # 输出 [0, 2, 4, 6, 8]
1.2.2 字典(dict)
字典(dict)是一种键值对 (key-value)数据结构,使用 {}
作为表示。
1. 创建字典
python
# 创建字典
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
empty_dict = {} # 创建空字典
2. 键值对操作
python
# 访问字典元素
print(student["name"]) # 输出 Alice
# 添加或更新键值对
student["grade"] = "A" # 新增键值对
student["age"] = 26 # 更新 age 值
# 删除键值对
del student["major"]
print(student) # {'name': 'Alice', 'age': 26, 'grade': 'A'}
3. 字典合并
python
# 使用 update() 方法合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
print(dict1) # {'a': 1, 'b': 3, 'c': 4}
1.2.3 元组(tuple)和集合(set)
1. 元组(tuple)
元组是不可变的序列,常用于存储不可变的数据。
python
# 创建元组
tup = (1, 2, 3, "hello")
# 访问元组元素
print(tup[0]) # 输出 1
# 元组解包
a, b, c, d = tup
print(a, d) # 输出 1 hello
2. 集合(set)
集合是无序 、唯一的元素集合。
python
# 创建集合
s = {1, 2, 3, 4, 4, 2}
print(s) # 输出 {1, 2, 3, 4}(去重)
# 集合运算
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1, 2}
通过本章的学习,我们了解了 Python 中的四种主要数据结构:列表、字典、元组和集合。这些数据结构是编写 Python 代码的基础,掌握它们的使用方法将为后续的编程提供强大的支持。建议多实践代码,加深理解!