什么是迭代器?
迭代器是Python中用于遍历集合元素的对象。任何实现了__iter__()和__next__()方法的对象都是迭代器。迭代器遵循迭代器协议,允许逐个访问容器中的元素。

迭代器的基本概念
迭代器协议

class MyIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        value = self.data[self.index]
        self.index += 1
        return value

# 使用自定义迭代器
my_iter = MyIterator([1, 2, 3, 4, 5])
for item in my_iter:
    print(item)  # 输出: 1 2 3 4 5

迭代器 vs 可迭代对象
关键区别

# 列表是可迭代对象,但不是迭代器
my_list = [1, 2, 3]
print(hasattr(my_list, '__iter__'))  # True - 可迭代
print(hasattr(my_list, '__next__'))  # False - 不是迭代器

# 通过iter()函数获取迭代器
list_iterator = iter(my_list)
print(hasattr(list_iterator, '__next__'))  # True - 现在是迭代器

# 遍历演示
print("直接遍历列表:")
for item in my_list:
    print(item)

print("通过迭代器遍历:")
iterator = iter(my_list)
try:
    while True:
        print(next(iterator))
except StopIteration:
    pass

内置迭代器用法
常见数据类型的迭代

# 字符串迭代
text = "Hello"
for char in text:
    print(char)

# 字典迭代
person = {"name": "Alice", "age": 25, "city": "Beijing"}
for key in person:  # 迭代键
    print(key)

for value in person.values():  # 迭代值
    print(value)

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

文件迭代器

# 文件对象本身就是迭代器
with open('example.txt', 'w') as f:
    f.write("Line 1\nLine 2\nLine 3")

with open('example.txt', 'r') as f:
    for line in f:  # 逐行迭代,内存高效
        print(line.strip())

实用迭代器工具
enumerate() - 带索引的迭代

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 输出:
# 0: apple
# 1: banana
# 2: cherry

# 可以指定起始索引
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}: {fruit}")

zip() - 并行迭代

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['Beijing', 'Shanghai', 'Guangzhou']

for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} years old and lives in {city}")
# 输出:
# Alice is 25 years old and lives in Beijing
# Bob is 30 years old and lives in Shanghai
# Charlie is 35 years old and lives in Guangzhou

reversed() - 反向迭代

numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
    print(num)  # 输出: 5, 4, 3, 2, 1

# 也适用于字符串
text = "Python"
for char in reversed(text):
    print(char)  # 输出: n, o, h, t, y, P

自定义迭代器示例
范围迭代器

class RangeIterator:
    def __init__(self, start, end, step=1):
        self.current = start
        self.end = end
        self.step = step
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.step > 0 and self.current >= self.end:
            raise StopIteration
        elif self.step < 0 and self.current <= self.end:
            raise StopIteration
        
        current_val = self.current
        self.current += self.step
        return current_val

# 使用自定义范围迭代器
for i in RangeIterator(1, 5):
    print(i)  # 输出: 1, 2, 3, 4

for i in RangeIterator(5, 0, -1):
    print(i)  # 输出: 5, 4, 3, 2, 1

斐波那契数列迭代器

class FibonacciIterator:
    def __init__(self, max_count):
        self.max_count = max_count
        self.count = 0
        self.a, self.b = 0, 1
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.count >= self.max_count:
            raise StopIteration
        
        if self.count == 0:
            self.count += 1
            return self.a
        elif self.count == 1:
            self.count += 1
            return self.b
        else:
            self.a, self.b = self.b, self.a + self.b
            self.count += 1
            return self.b

# 生成前10个斐波那契数
fib_iter = FibonacciIterator(10)
fib_numbers = list(fib_iter)
print(fib_numbers)  # 输出: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

迭代器的高级用法
itertools 模块

import itertools

# 无限迭代器
counter = itertools.count(start=10, step=2)
print([next(counter) for _ in range(5)])  # [10, 12, 14, 16, 18]

# 循环迭代器
cycler = itertools.cycle('ABC')
print([next(cycler) for _ in range(6)])  # ['A', 'B', 'C', 'A', 'B', 'C']

# 排列组合
letters = ['A', 'B', 'C']
perms = itertools.permutations(letters, 2)
print(list(perms))  # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

迭代器的优势
1.内存高效:不需要一次性加载所有数据

2.惰性求值:按需计算,提高性能

3.统一接口:一致的遍历方式

4.无限序列:可以表示无限的数据流

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐