Python中的itertools模块提供了许多用于处理迭代器的函数,
这些函数可以用于生成各种类型的迭代器,例如排列、组合、重复等。
以下是一些常用的itertools函数及其用法:
- count(start, step)
从start开始,以step为步长生成一个无限的整数序列。
import itertools
for i in itertools.count(1):
print(i) # 1 2 3 4 5 6 7 8 9 10
- cycle(iterable)
对iterable进行循环迭代,返回一个无限的迭代器。
import itertools
for i in itertools.cycle([1, 2, 3]):
print(i) # 1 2 3 1 2 3 1 2 3
- repeat(object, times)
将object重复times次,返回一个迭代器。
import itertools
for i in itertools.repeat('a', 5):
print(i) #a a a a a
- permutations(iterable, r=None)
返回iterable中所有长度为r的元素排列组成的迭代器
如果r为None,则返回所有可能的排列。
import itertools
for i in itertools.permutations('abc', 2):
print(i)
#('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b')
- combinations(iterable, r)
返回iterable中所有长度为r的元素组合组成的迭代器。
import itertools
for i in itertools.combinations('abc', 2):
print(i)
#('a', 'b') ('a', 'c') ('b', 'c')
6.product(*iterables, repeat=1)
返回iterables中所有元素的笛卡尔积组成的迭代器。
如果repeat为1,则每个元素只出现一次;
如果repeat为任意正整数n,则每个元素出现n次。
import itertools
for i in itertools.product(['a', 'b'], ['x', 'y']):
print(i)
# ('a', 'x') ('a', 'y') ('b', 'x') ('b', 'y')