一、列表 (List) - 灵活多变的储物柜
列表是 Python 中最常用、最灵活的数据容器。
- 核心特点 :有序的 、可变的 (Mutable) 、允许重复元素。
- 定义符号 :中括号
[]
1. 创建列表
python
my_list = [1, 'hello', 3.14, True, 'hello']
empty_list = []
2. 列表相关操作 (增、删、改、查)
python
# --- 增 ---
my_list.append('new') # 在末尾添加 -> [1, 'hello', 3.14, True, 'hello', 'new']
my_list.insert(1, 'world') # 在索引1处插入 -> [1, 'world', 'hello', ...]
my_list.extend([10, 20]) # 合并另一个列表 -> [..., 'new', 10, 20]
# --- 删 ---
my_list.pop() # 删除并返回末尾元素 -> 返回 20
my_list.pop(1) # 删除并返回索引1的元素 -> 返回 'world'
my_list.remove('hello') # 删除第一个匹配的'hello'
del my_list[0] # 使用del关键字删除索引0的元素
# --- 改 ---
my_list[0] = 'Python' # 修改索引0的元素
# --- 查 ---
print(my_list[0]) # 按索引访问
print('Python' in my_list) # 检查元素是否存在 -> True
print(my_list.index('Python')) # 查找元素的索引
print(my_list.count('hello')) # 统计元素出现的次数
3. 列表遍历 (Traversal)
python
fruits = ['apple', 'banana', 'cherry']
# 方式一:直接遍历元素 (最常用)
for fruit in fruits:
print(fruit)
# 方式二:通过索引遍历
for i in range(len(fruits)):
print(f"索引 {i}: {fruits[i]}")
# 方式三:同时获取索引和元素 (推荐)
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")
4. 列表生成式 (List Comprehension)
这是一种非常强大、简洁的创建列表的方式。
- 基本语法 :
[expression for item in iterable]
- 带条件语法 :
[expression for item in iterable if condition]
python
# 示例1: 生成0-9的平方
squares = [x * x for x in range(10)]
# -> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 示例2: 从列表中筛选出偶数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
# -> [2, 4, 6]
# 示例3: 复杂表达式
words = ['hello', 'world', 'python']
upper_words = [word.upper() for word in words]
# -> ['HELLO', 'WORLD', 'PYTHON']





二、元组 (Tuple) - 不可变的保险箱
元组与列表类似,但一旦创建就无法修改。
- 核心特点 :有序的 、不可变的 (Immutable) 、允许重复元素。
- 定义符号 :小括号
()
1. 创建元组
python
my_tuple = (1, 'hello', 3.14, True, 'hello')
empty_tuple = ()
# 特别注意:创建单个元素的元组,必须加逗号
single_tuple = (1,)
not_a_tuple = (1) # 这是一个整数
2. 元组相关操作
元组没有增、删、改的方法。主要操作是查询。
python
print(my_tuple[0]) # 访问元素
print('hello' in my_tuple) # 检查是否存在
print(my_tuple.count('hello')) # 统计出现次数
print(my_tuple.index('hello')) # 查找索引
3. 元组遍历
与列表完全相同。
python
coordinates = (10, 20, 30)
for c in coordinates:
print(c)
4. "元组生成式"? (一个常见的误解)
Python 没有 直接的元组生成式。使用小括号的生成式语法创建的是一个 生成器对象 (Generator Object),而不是元组。
python
# 这不是元组生成式,而是一个生成器!
gen_obj = (x * x for x in range(5))
print(gen_obj) # -> <generator object <genexpr> at 0x...>
# 生成器是可迭代的,一次产生一个值,非常节省内存
for item in gen_obj:
print(item) # 会依次打印 0, 1, 4, 9, 16
# 如果你真的想通过生成式得到一个元组,需要这样做:
my_tuple_from_gen = tuple(x * x for x in range(5))
print(my_tuple_from_gen) # -> (0, 1, 4, 9, 16, 25)
代码运行图:


三、字典 (Dictionary) - 标签化的档案柜
字典存储的是键值对 (key-value pairs)。
- 核心特点 :键值对存储 、键必须唯一且不可变 、值可以任意 、Python 3.7+ 后是有序的(按插入顺序)。
- 定义符号 :大括号
{}
1. 创建字典
python
person = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
empty_dict = {}
2. 字典相关操作
python
# --- 增 / 改 ---
person['age'] = 26 # 修改已存在的键
person['email'] = 'alice@a.com' # 添加新的键值对
person.update({'country': 'USA', 'age': 27}) # 批量更新/添加
# --- 删 ---
del person['city']
removed_age = person.pop('age') # 删除并返回age的值
last_item = person.popitem() # 删除并返回最后一对键值
# --- 查 ---
print(person['name']) # 通过键访问值 (如果键不存在会报错)
print(person.get('name')) # 安全访问 (如果键不存在返回None)
print(person.get('job', 'N/A')) # 安全访问,并提供默认值
3. 字典遍历
python
# 方式一:遍历键 (默认)
for key in person:
print(f"Key: {key}, Value: {person[key]}")
# 方式二:遍历值
for value in person.values():
print(value)
# 方式三:遍历键值对 (最常用,推荐)
for key, value in person.items():
print(f"Key: {key}, Value: {value}")
4. 字典生成式
与列表生成式类似,用于快速创建字典。
- 语法 :
{key_expression: value_expression for item in iterable}
python
# 示例1: 创建数字及其平方的字典
squares_dict = {x: x*x for x in range(5)}
# -> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 示例2: 从列表中创建字典
fruits = ['apple', 'banana', 'cherry']
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
# -> {'apple': 5, 'banana': 6, 'cherry': 6}



四、集合 (Set) - 无重复的数学集
集合是一个无序且不含重复元素的容器。
- 核心特点 :无序的 、可变的 、元素唯一不重复。
- 定义符号 :大括号
{}
,但空集合必须用set()
。 - 只能存储不可变数据类型
1. 创建集合
python
my_set = {1, 2, 3, 2, 1} # 重复元素会被自动去除
print(my_set) # -> {1, 2, 3}
# 创建空集合必须用 set()
empty_set = set()
wrong_empty_set = {} # 这是一个空字典!
2. 集合相关操作
集合的核心在于其数学运算。
python
# --- 增 ---
my_set.add(4) # 添加单个元素
my_set.update([4, 5, 6]) # 添加多个元素
# --- 删 ---
my_set.remove(6) # 删除元素 (如果不存在会报错)
my_set.discard(5) # 安全删除 (如果不存在不报错)
my_set.pop() # 随机删除一个元素并返回
# --- 改 ---
my_set.clear # 清空所有元素
# --- 核心:数学运算 ---
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# 交集 (&)
print(set_a.intersection(set_b)) # -> {3, 4}
print(set_a & set_b)
# 并集 (|)
print(set_a.union(set_b)) # -> {1, 2, 3, 4, 5, 6}
print(set_a | set_b)
# 差集 (-)
print(set_a.difference(set_b)) # -> {1, 2} (a中有,b中没有)
print(set_a - set_b)
# 对称差集 (^)
print(set_a.symmetric_difference(set_b)) # -> {1, 2, 5, 6} (只在a或只在b中)
print(set_a ^ set_b)
3. 集合遍历与生成式
- 遍历 :
for item in my_set:
- 生成式 :
{expression for item in iterable}
,常用于去重。
python
#遍历
for index,item in emumerate(my_set):
print(index,'--->',item)
# 集合生成式,从列表中提取唯一的偶数
numbers = [1, 2, 3, 4, 5, 6, 2, 4]
unique_evens = {num for num in numbers if num % 2 == 0}
# -> {2, 4, 6}
总结对比
特性 | 列表 (List) | 元组 (Tuple) | 字典 (Dictionary) | 集合 (Set) |
---|---|---|---|---|
定义符号 | [] |
() |
{key: value} |
{} 或 set() |
有序性 | 有序 | 有序 | Python 3.7+ 有序 | 无序 |
可变性 | 可变 | 不可变 | 可变 | 可变 |
重复元素 | 允许 | 允许 | 键不许重复,值允许 | 不允许 |
主要特点 | 灵活的动态数组 | 只读列表,性能好 | 键值对映射 | 唯一元素,数学运算 |