当前位置:首页 > Python > 正文

Python迭代函数完全指南:掌握高效循环技巧 | Python教程

Python迭代函数完全指南:掌握高效循环技巧

什么是迭代?

在Python中,迭代是访问集合元素的一种方式。迭代器是一个可以记住遍历位置的对象,从集合的第一个元素开始访问,直到所有元素被访问完结束。

Python中常见的可迭代对象包括:

  • 列表(list)
  • 元组(tuple)
  • 字符串(str)
  • 字典(dict)
  • 集合(set)
  • 文件对象
  • 生成器(generator)

核心迭代函数详解

1. enumerate() - 带索引的迭代

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}")

# 输出:
# #1: apple
# #2: banana
# #3: cherry

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")

# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old

# 多个序列
for name, age, city in zip(names, ages, cities):
    print(f"{name} ({age}) lives in {city}")

# 输出:
# Alice (25) lives in New York
# Bob (30) lives in London
# Charlie (35) lives in Paris

# 解压为列表
zipped = list(zip(names, ages, cities))
print(zipped)  # [('Alice', 25, 'New York'), ('Bob', 30, 'London'), ('Charlie', 35, 'Paris')]

3. map() - 应用函数到每个元素

map() 函数会根据提供的函数对指定序列做映射,返回一个迭代器。

# 将数字列表转换为字符串
numbers = [1, 2, 3, 4, 5]
str_numbers = list(map(str, numbers))
print(str_numbers)  # ['1', '2', '3', '4', '5']

# 计算平方
def square(x):
    return x ** 2

squares = list(map(square, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# 使用lambda表达式
cubes = list(map(lambda x: x**3, numbers))
print(cubes)  # [1, 8, 27, 64, 125]

# 多个序列
a = [1, 2, 3]
b = [4, 5, 6]
result = list(map(lambda x, y: x + y, a, b))
print(result)  # [5, 7, 9]

4. filter() - 过滤序列元素

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的迭代器。

# 过滤偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4, 6, 8, 10]

# 过滤非空字符串
words = ["hello", "", "world", " ", "python", None, "filter"]
non_empty = list(filter(None, words))  # None表示过滤掉布尔值为False的元素
print(non_empty)  # ['hello', 'world', ' ', 'python', 'filter']

# 自定义过滤函数
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

primes = list(filter(is_prime, range(1, 50)))
print(primes)  # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

5. iter() 和 next() - 手动控制迭代

iter() 函数用于生成迭代器,next() 函数用于获取迭代器的下一个元素。

# 基本用法
fruits = ['apple', 'banana', 'cherry']
fruit_iter = iter(fruits)

print(next(fruit_iter))  # apple
print(next(fruit_iter))  # banana
print(next(fruit_iter))  # cherry
# print(next(fruit_iter))  # 抛出StopIteration异常

# 自定义迭代器
class CountDown:
    def __init__(self, start):
        self.current = start
        
    def __iter__(self):
        return self
        
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        else:
            self.current -= 1
            return self.current + 1

# 使用自定义迭代器
counter = CountDown(3)
for num in counter:
    print(num)
    
# 输出:
# 3
# 2
# 1

6. reversed() - 反向迭代

reversed() 函数返回一个反转的迭代器。

# 反转列表
numbers = [1, 2, 3, 4, 5]
reversed_numbers = list(reversed(numbers))
print(reversed_numbers)  # [5, 4, 3, 2, 1]

# 反转字符串
text = "Python"
reversed_text = ''.join(reversed(text))
print(reversed_text)  # nohtyP

# 自定义类的反转
class CountUp:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        
    def __iter__(self):
        self.current = self.start
        return self
        
    def __next__(self):
        if self.current > self.end:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1
            
    def __reversed__(self):
        self.current = self.end
        while self.current >= self.start:
            yield self.current
            self.current -= 1

# 使用自定义反转
counter = CountUp(1, 5)
for num in reversed(counter):
    print(num)
    
# 输出:
# 5
# 4
# 3
# 2
# 1

迭代函数使用技巧与最佳实践

  • 惰性求值:Python的迭代器是惰性的,只在需要时生成值,节省内存
  • 组合使用:迭代函数可以组合使用,如 map(filter(...), ...)
  • 生成器表达式:对于简单操作,生成器表达式比map/filter更简洁
  • 内存效率:在处理大型数据集时,优先使用迭代器而不是列表
  • 异常处理:使用try-except处理StopIteration异常
  • 可迭代性检查:使用from collections.abc import Iterable检查对象是否可迭代

组合使用示例

# 组合使用enumerate和zip
students = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]

for i, (name, score) in enumerate(zip(students, scores), start=1):
    print(f"{i}. {name}: {score}")

# 输出:
# 1. Alice: 85
# 2. Bob: 92
# 3. Charlie: 78

# 组合使用map和filter
numbers = range(1, 11)
# 获取偶数的平方
result = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(result)  # [4, 16, 36, 64, 100]

# 使用生成器表达式(更Pythonic的方式)
result = (x**2 for x in numbers if x % 2 == 0)
print(list(result))  # [4, 16, 36, 64, 100]

总结

Python提供了多种强大的迭代函数,可以大大简化循环操作并提高代码效率。掌握这些函数的使用方法,能够让你:

  1. 编写更简洁、更Pythonic的代码
  2. 提高代码的可读性和可维护性
  3. 处理大型数据集时更高效地使用内存
  4. 实现复杂的迭代逻辑

记住这些核心迭代函数:

函数 描述 典型应用
enumerate() 获取元素和索引 循环时需要索引位置
zip() 并行迭代多个序列 同时处理多个相关列表
map() 应用函数到序列元素 批量转换数据
filter() 过滤序列元素 筛选满足条件的元素
iter()/next() 手动控制迭代 自定义迭代行为
reversed() 反向迭代 从后向前处理序列

发表评论