Python高级特性:迭代完全指南
深入理解Python中的迭代机制
前言
迭代是Python编程中的核心概念,它允许我们优雅地遍历各种数据集合。无论是列表、字典还是字符串,Python都提供了统一而简洁的迭代语法。
本文将系统讲解迭代的基本概念、各种数据类型的迭代方式、高级迭代技巧以及最佳实践,帮助你写出更Pythonic的代码。
一、什么是迭代?
迭代是指通过循环遍历一个可迭代对象中的元素的过程。在Python中,迭代通常使用for...in语句实现。
# 最简单的迭代示例
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
输出:
apple
banana
orange
📌 核心概念:可迭代对象(Iterable)是指实现了
__iter__()方法的对象,它可以被for循环遍历。
二、基本数据类型的迭代
2.1 迭代列表(List)
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
2.2 迭代元组(Tuple)
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
2.3 迭代字符串(String)
字符串也是可迭代对象,每次迭代返回一个字符:
text = "Python"
for char in text:
print(char, end='-') # P-y-t-h-o-n-
三、字典(Dict)的迭代
字典的迭代方式最为灵活,有三种常见模式:
3.1 默认迭代:键(keys)
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 默认迭代键
for key in person:
print(key)
# 等价于
for key in person.keys():
print(key)
输出:
name
age
city
3.2 迭代值(values)
for value in person.values():
print(value)
输出:
Alice
25
New York
3.3 同时迭代键和值(items)
for key, value in person.items():
print(f"{key}: {value}")
输出:
name: Alice
age: 25
city: New York
四、判断可迭代对象
要检查一个对象是否可迭代,可以使用collections.abc模块中的Iterable类:
from collections.abc import Iterable
# 测试各种类型
print(isinstance('abc', Iterable)) # True - 字符串可迭代
print(isinstance([1, 2, 3], Iterable)) # True - 列表可迭代
print(isinstance(123, Iterable)) # False - 数字不可迭代
print(isinstance({'a': 1}, Iterable)) # True - 字典可迭代
print(isinstance((1, 2), Iterable)) # True - 元组可迭代
五、高级迭代技巧
5.1 带索引的迭代:enumerate()
当需要同时获取索引和元素时,使用enumerate():
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# 可以指定起始索引
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
输出:
Index 0: apple
Index 1: banana
Index 2: orange
1. apple
2. banana
3. orange
5.2 同时迭代多个序列:zip()
zip()函数可以将多个序列并行迭代:
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['New York', 'London', 'Paris']
# 同时迭代两个序列
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 同时迭代三个序列
for name, age, city in zip(names, ages, cities):
print(f"{name} ({age}) lives in {city}")
输出:
Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old
Alice (25) lives in New York
Bob (30) lives in London
Charlie (35) lives in Paris
5.3 反向迭代:reversed()
numbers = [1, 2, 3, 4, 5]
# 反向迭代
for num in reversed(numbers):
print(num, end=' ') # 5 4 3 2 1
# 字符串反向
text = "Python"
print(''.join(reversed(text))) # nohtyP
5.4 排序后迭代:sorted()
numbers = [3, 1, 4, 1, 5, 9, 2]
# 升序迭代
for num in sorted(numbers):
print(num, end=' ') # 1 1 2 3 4 5 9
# 降序迭代
for num in sorted(numbers, reverse=True):
print(num, end=' ') # 9 5 4 3 2 1 1
# 对字典按键排序
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key in sorted(person.keys()):
print(f"{key}: {person[key]}")
5.5 同时迭代多个变量
Python支持在迭代中同时解包多个变量:
# 迭代元组列表
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
print(f"x: {x}, y: {y}")
# 迭代列表的列表
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for col in row:
print(col, end=' ') # 1 2 3 4 5 6 7 8 9
print()
六、实践练习:查找列表的最小和最大值
def findMinAndMax(L):
"""查找列表的最小值和最大值"""
if not L: # 处理空列表
return (None, None)
min_val = max_val = L[0]
for num in L:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
return (min_val, max_val)
# 测试用例
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!') # 输出:测试成功!
# 使用内置函数更简单
def find_min_max_builtin(L):
if not L:
return (None, None)
return (min(L), max(L))
七、迭代器与可迭代对象
7.1 概念区分
| 概念 | 说明 | 示例 |
|---|---|---|
| 可迭代对象(Iterable) | 实现了__iter__()方法的对象 | list, tuple, dict, str |
| 迭代器(Iterator) | 实现了__iter__()和__next__()方法的对象 | iter()函数的返回值 |
7.2 手动迭代
# 使用iter()获取迭代器
fruits = ['apple', 'banana', 'orange']
iterator = iter(fruits)
# 手动调用next()获取元素
print(next(iterator)) # apple
print(next(iterator)) # banana
print(next(iterator)) # orange
# 超出范围会抛出StopIteration
# print(next(iterator)) # StopIteration
八、性能与最佳实践
8.1 迭代效率对比
| 迭代方式 | 内存占用 | 适用场景 |
|---|---|---|
for item in list | 高(全部加载) | 小到中型数据集 |
for item in generator | 低(惰性求值) | 大数据集或无限序列 |
enumerate() | 低 | 需要索引时 |
zip() | 低 | 并行遍历多个序列 |
8.2 生成器表达式(惰性迭代)
# 列表推导式(立即计算,占用内存)
squares_list = [x**2 for x in range(1000000)]
# 生成器表达式(惰性计算,节省内存)
squares_gen = (x**2 for x in range(1000000))
# 生成器只在迭代时计算值
for sq in squares_gen:
if sq > 100:
break
print(sq, end=' ') # 0 1 4 9 16 25 36 49 64 81 100
8.3 迭代最佳实践
# ✅ 好的做法
# 1. 使用enumerate()获取索引
for i, item in enumerate(data):
process(i, item)
# 2. 使用zip()并行遍历
for name, score in zip(names, scores):
print(f"{name}: {score}")
# 3. 使用生成器处理大数据
def read_large_file(file_path):
with open(file_path) as f:
for line in f:
yield line.strip()
# ❌ 避免的做法
# 1. 使用range(len())遍历(不Pythonic)
for i in range(len(data)):
process(data[i]) # 应该用 for item in data
# 2. 手动维护索引
i = 0
for item in data:
process(i, item)
i += 1 # 应该用 enumerate()
# 3. 不必要的列表转换
total = sum([x**2 for x in range(1000)]) # 创建了临时列表
total = sum(x**2 for x in range(1000)) # 使用生成器更好
九、总结
| 迭代方式 | 语法 | 适用场景 |
|---|---|---|
| 基本迭代 | for item in iterable: | 遍历序列、字符串 |
| 字典键迭代 | for key in dict: | 处理字典键 |
| 字典值迭代 | for value in dict.values(): | 处理字典值 |
| 键值对迭代 | for k, v in dict.items(): | 同时处理键和值 |
| 带索引迭代 | for i, item in enumerate(seq): | 需要元素位置 |
| 并行迭代 | for a, b in zip(seq1, seq2): | 同步遍历多个序列 |
| 反向迭代 | for item in reversed(seq): | 反向遍历 |
| 排序迭代 | for item in sorted(seq): | 有序遍历 |
核心要点:
- ✅
for...in是Python中唯一的迭代语法 - ✅ 任何可迭代对象都可以被
for循环遍历 - ✅ 字典默认迭代键,但提供了
.values()和.items() - ✅
enumerate()同时获取索引和元素 - ✅
zip()可以并行遍历多个序列 - ✅ 使用生成器表达式处理大数据集
掌握迭代技巧是写出Pythonic代码的基础,它能让你的代码更简洁、更高效、更易读。
📚 相关推荐阅读
💡 Python 学习不走弯路! 体系化实战路线:基础语法 · 异步Web开发 · 数据采集 · 计算机视觉 · NLP · 大模型RAG实战 —— 全在「道满PythonAI」! 点赞 + 关注,持续更新干货!
如果这篇文章对你有帮助,欢迎点赞、评论、收藏,你的支持是我持续分享的动力!🎉