跳到主要内容

Python 数据结构

Python 内置了多种数据结构,用于存储和组织数据。本章将介绍列表、元组、字典和集合。

列表(List)

列表是最常用的数据结构,可以存储有序的元素序列。

创建列表

# 空列表
empty = []

# 有元素的列表
fruits = ["苹果", "香蕉", "橙子"]

# 混合类型
mixed = [1, "hello", 3.14, True]

# 使用 list() 构造函数
numbers = list(range(5)) # [0, 1, 2, 3, 4]

访问元素

fruits = ["苹果", "香蕉", "橙子", "葡萄"]

# 索引访问(从 0 开始)
print(fruits[0]) # 苹果
print(fruits[1]) # 香蕉

# 负索引(从 -1 开始,表示最后一个元素)
print(fruits[-1]) # 葡萄
print(fruits[-2]) # 橙子

切片操作

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(numbers[2:5]) # [2, 3, 4] - 索引 2 到 4
print(numbers[:5]) # [0, 1, 2, 3, 4] - 从开始到 4
print(numbers[5:]) # [5, 6, 7, 8, 9] - 从 5 到末尾
print(numbers[::2]) # [0, 2, 4, 6, 8] - 步长为 2
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] - 倒序

修改列表

fruits = ["苹果", "香蕉", "橙子"]

# 修改元素
fruits[0] = "葡萄"
print(fruits) # ['葡萄', '香蕉', '橙子']

# 添加元素
fruits.append("草莓") # 末尾添加
print(fruits) # ['葡萄', '香蕉', '橙子', '草莓']

fruits.insert(1, "桃子") # 指定位置插入
print(fruits) # ['葡萄', '桃子', '香蕉', '橙子', '草莓']

# 删除元素
fruits.remove("香蕉") # 删除第一个匹配的元素
print(fruits) # ['葡萄', '桃子', '橙子', '草莓']

del fruits[0] # 删除指定位置的元素
print(fruits) # ['桃子', '橙子', '草莓']

popped = fruits.pop() # 弹出并返回最后一个元素
print(popped) # 草莓
print(fruits) # ['桃子', '橙子']

# 清空列表
fruits.clear()
print(fruits) # []

列表操作

# 连接列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]

# 重复列表
repeated = [1, 2] * 3
print(repeated) # [1, 2, 1, 2, 1, 2]

# 列表推导式
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]

列表方法

方法描述示例
append()末尾添加元素list.append(1)
insert()指定位置插入list.insert(0, 1)
remove()删除第一个匹配项list.remove(1)
pop()弹出并返回元素list.pop()
clear()清空列表list.clear()
index()查找元素索引list.index(1)
count()统计元素出现次数list.count(1)
sort()排序list.sort()
reverse()反转list.reverse()
copy()浅拷贝new_list = list.copy()

遍历列表

fruits = ["苹果", "香蕉", "橙子"]

# 直接遍历
for fruit in fruits:
print(fruit)

# 带索引遍历
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

# 使用索引遍历
for i in range(len(fruits)):
print(fruits[i])

元组(Tuple)

元组是不可变的列表,一旦创建就不能修改。

创建元组

# 空元组
empty = ()

# 单元素元组(需要加逗号)
single = (1,)

# 多元素元组
point = (1, 2, 3)
mixed = (1, "hello", 3.14)

# 省略括号
coordinates = 1, 2, 3

# 使用 tuple() 构造函数
numbers = tuple([1, 2, 3])

访问元组

point = (1, 2, 3)

print(point[0]) # 1
print(point[-1]) # 3
print(point[1:3]) # (2, 3)

元组操作

# 连接元组
t1 = (1, 2, 3)
t2 = (4, 5, 6)
combined = t1 + t2
print(combined) # (1, 2, 3, 4, 5, 6)

# 重复元组
repeated = (1, 2) * 3
print(repeated) # (1, 2, 1, 2, 1, 2)

# 解包
point = (1, 2, 3)
x, y, z = point
print(x, y, z) # 1 2 3

# 部分解包
a, *b = (1, 2, 3, 4, 5)
print(a) # 1
print(b) # [2, 3, 4, 5]

元组方法

point = (1, 2, 3, 2, 1)

print(point.count(2)) # 2 - 元素出现次数
print(point.index(3)) # 2 - 元素首次出现的索引

字典(Dict)

字典是键值对的无序集合,通过键来访问值。

创建字典

# 空字典
empty = {}

# 有数据的字典
person = {"name": "张三", "age": 20, "city": "北京"}

# 使用 dict() 构造函数
person = dict(name="张三", age=20, city="北京")

# 使用 fromkeys()
keys = ["name", "age", "city"]
default_dict = dict.fromkeys(keys, "未知")
print(default_dict) # {'name': '未知', 'age': '未知', 'city': '未知'}

访问字典

person = {"name": "张三", "age": 20, "city": "北京"}

# 通过键访问
print(person["name"]) # 张三
print(person["age"]) # 20

# 使用 get() 方法(更安全)
print(person.get("name")) # 张三
print(person.get("gender", "未知")) # 未知(默认值)

修改字典

person = {"name": "张三", "age": 20}

# 添加/修改键值对
person["city"] = "北京"
print(person) # {'name': '张三', 'age': 20, 'city': '北京'}

# 删除键值对
del person["age"]
print(person) # {'name': '张三', 'city': '北京'}

# pop() - 删除并返回值
age = person.pop("city")
print(age) # 北京

# popitem() - 删除并返回最后一个键值对
item = {"a": 1, "b": 2}.popitem()
print(item) # ('b', 2)

# clear() - 清空字典
person.clear()
print(person) # {}

字典方法

person = {"name": "张三", "age": 20, "city": "北京"}

# keys() - 所有键
print(person.keys()) # dict_keys(['name', 'age', 'city'])

# values() - 所有值
print(person.values()) # dict_values(['张三', 20, '北京'])

# items() - 所有键值对
print(person.items()) # dict_items([('name', '张三'), ('age', 20), ('city', '北京')])

# update() - 合并字典
person.update({"country": "中国", "age": 21})
print(person) # {'name': '张三', 'age': 21, 'city': '北京', 'country': '中国'}

# copy() - 浅拷贝
person_copy = person.copy()

遍历字典

person = {"name": "张三", "age": 20, "city": "北京"}

# 遍历键
for key in person:
print(key)

for key in person.keys():
print(key)

# 遍历值
for value in person.values():
print(value)

# 遍历键值对
for key, value in person.items():
print(f"{key}: {value}")

字典推导式

# 创建字典
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 筛选
d = {"a": 1, "b": 2, "c": 3, "d": 4}
filtered = {k: v for k, v in d.items() if v > 2}
print(filtered) # {'c': 3, 'd': 4}

集合(Set)

集合是无序且不重复的元素集合。

创建集合

# 空集合(不能用 {},{} 创建的是字典)
empty = set()

# 有元素的集合
fruits = {"苹果", "香蕉", "橙子"}

# 使用 set() 构造函数
numbers = set([1, 2, 3, 4, 5])

# 集合推导式
squares = {x**2 for x in range(5)}
print(squares) # {0, 1, 4, 9, 16}

集合操作

# 添加元素
fruits = {"苹果", "香蕉"}
fruits.add("橙子")
print(fruits) # {'苹果', '香蕉', '橙子'}

# 删除元素
fruits.remove("苹果") # 如果不存在会抛出异常
fruits.discard("葡萄") # 如果不存在不会报错

# 随机删除并返回一个元素
popped = fruits.pop()

# 清空集合
fruits.clear()

集合运算

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 并集
union = set1 | set2
union = set1.union(set2)
print(union) # {1, 2, 3, 4, 5, 6}

# 交集
intersection = set1 & set2
intersection = set1.intersection(set2)
print(intersection) # {3, 4}

# 差集
difference = set1 - set2
difference = set1.difference(set2)
print(difference) # {1, 2}

# 对称差集(并集减交集)
sym_diff = set1 ^ set2
sym_diff = set1.symmetric_difference(set2)
print(sym_diff) # {1, 2, 5, 6}

# 子集和超集
set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
print(set_a.issubset(set_b)) # True
print(set_b.issuperset(set_a)) # True

遍历集合

fruits = {"苹果", "香蕉", "橙子"}

for fruit in fruits:
print(fruit)

数据结构比较

特性列表元组字典集合
有序
可变
索引访问✓ (键)
重复元素键不可重复
适用场景有序序列固定数据键值映射去重、集合运算

小结

本章我们学习了:

  1. 列表的创建、访问、修改和操作
  2. 元组的创建、访问和解包
  3. 字典的创建、访问、修改和遍历
  4. 集合的创建和集合运算
  5. 列表推导式、字典推导式和集合推导式

练习

  1. 创建一个列表,存储 1-10 的平方
  2. 统计字符串中每个字符出现的次数
  3. 实现两个集合的交集、并集、差集运算
  4. 实现通讯录功能(添加、删除、查询、修改)