如何使用Python的itertools模块处理复杂的迭代模式?

发布时间:
2024-10-19 16:29
阅读量:
1

itertools.chain() - 链接多个迭代器

chain() 可以把多个可迭代对象(如列表、元组等)连接成一个迭代器。

import itertools # 示例: 将两个列表连接成一个 list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] # 使用chain连接两个列表 combined = itertools.chain(list1, list2) # 打印结果 print(list(combined)) # 输出: [1, 2, 3, 'a', 'b', 'c']

itertools.product() - 笛卡尔积

product() 用于计算多个迭代器的笛卡尔积(类似于多重循环中的所有可能组合)

import itertools # 示例: 计算两个列表的笛卡尔积 list1 = [1, 2] list2 = ['a', 'b'] # 计算笛卡尔积 result = itertools.product(list1, list2) # 打印结果 print(list(result)) # 输出: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

itertools.permutations() - 全排列

permutations() 返回一个迭代器,其中包含给定可迭代对象中元素的所有可能排列。

import itertools # 示例: 计算一个列表的所有排列 list1 = [1, 2, 3] # 计算全排列 result = itertools.permutations(list1) # 打印结果 print(list(result)) # 输出: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

END