跳转至

Python迭代完整学习指南

1. 什么是迭代?想象一下...

想象你正在玩一个神奇的跳房子游戏!你一格一格地向前跳,每一步都是相似的动作,直到达到终点。这就像迭代:通过重复相同的操作步骤,一步一步地解决问题。

2. 基本迭代概念

2.1. for循环迭代

# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
    print(fruit)

# 遍历字符串
for char in "Python":
    print(char)

# 使用range()
for i in range(5):
    print(i)  # 输出:0, 1, 2, 3, 4

2.2. while循环迭代

# 基本while循环
count = 0
while count < 5:
    print(count)
    count += 1

# 带条件的while循环
number = 10
while number > 0:
    print(number)
    number -= 2

3. 高级迭代技巧

3.1. 迭代器和生成器

# 创建迭代器
class CountUp:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.end:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

# 使用迭代器
counter = CountUp(0, 3)
for num in counter:
    print(num)  # 输出:0, 1, 2, 3

# 生成器函数
def fibonacci_gen(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# 使用生成器
for num in fibonacci_gen(5):
    print(num)  # 输出:0, 1, 1, 2, 3

3.2. 列表推导式

# 基本列表推导式
squares = [x**2 for x in range(5)]
print(squares)  # 输出:[0, 1, 4, 9, 16]

# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # 输出:[0, 4, 16, 36, 64]

4. 实战应用

4.1. 文件处理

# 逐行读取文件
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

# 使用迭代器处理大文件
def read_large_file(file_path):
    with open(file_path, 'r') as file:
        while True:
            chunk = file.read(1024)  # 每次读取1KB
            if not chunk:
                break
            yield chunk

4.2. 数据处理

# 处理列表数据
numbers = [1, 2, 3, 4, 5]
processed = []
for num in numbers:
    if num % 2 == 0:
        processed.append(num * 2)
    else:
        processed.append(num + 1)
print(processed)  # 输出:[2, 4, 4, 8, 6]

# 使用zip处理多个列表
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

5. 性能优化

5.1. 迭代器vs列表

# 使用迭代器节省内存
def number_generator(n):
    for i in range(n):
        yield i

# 比较内存使用
numbers_list = list(range(1000000))  # 占用更多内存
numbers_gen = number_generator(1000000)  # 占用极少内存

5.2. 优化技巧

# 使用enumerate避免手动计数
fruits = ["苹果", "香蕉", "橙子"]
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# 使用itertools提高效率
from itertools import combinations
items = [1, 2, 3]
for combo in combinations(items, 2):
    print(combo)

6. 最佳实践

6.1. 代码风格

  • 选择合适的循环类型
  • 使用清晰的变量名
  • 适当添加注释

6.2. 性能考虑

  • 大数据集使用迭代器
  • 避免不必要的列表生成
  • 合理使用生成器

6.3. 调试技巧

  • 使用print语句跟踪
  • 设置适当的断点
  • 检查循环条件

7. 进一步学习