在Python的标准库当中有这么一个神奇的工具库,它能让你使用最简单的方式写出更简洁高效的代码,这就是itertools,使用这个工具能为你生成一个优雅的迭代器。
这个模块提供了一些工具来处理迭代器。 简单地说,迭代器是一种可以在 for
循环中使用的数据类型。 Python 中最常见的迭代器是列表。
可以在官网获得itertools
的全部用法。
product() 笛卡尔积
这个工具计算输入迭代器的笛卡尔积。 它等价于嵌套的 for
循环。例如,product(A, B)
返回((x,y) for x in A for y in B)
相同。
代码:
from itertools import product
prod = product([1, 2], [3, 4])
# 注意,我们将迭代器转换为列表以便打印
print(list(prod))
# 以允许迭代器的笛卡尔积,请指定重复次数
prod = product([1, 2], [3], repeat=2)
print(list(prod))
结果:
[(1, 3), (1, 4), (2, 3), (2, 4)]
[(1, 3, 1, 3), (1, 3, 2, 3), (2, 3, 1, 3), (2, 3, 2, 3)]
permutations() 排列
该函数返回迭代器中元素的所有可能排列(无重复元素)。
代码:
from itertools import permutations
perm = permutations([1, 2, 3])
print(list(perm))
# 可选参数:排列的长度。
perm = permutations([1, 2, 3], 2