python itertools 模块

itertools 模块的官方解释: Functional tools for creating and using iterators. (用于创建和使用迭代器的函数工具)

1.   product(*iterables, repeat=1) 

用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.即:  product(A, B) 和 ((x,y) for in for in B)一样.

例:

 1 '''
 2 第一个参数是可迭代器
 3 第二个参数的值是组合的长度
 4 '''
 5 from itertools import product
 6 for i in (x for x in product('ABCD', repeat=2)):
 7     print(i)
 8 
 9 # 输出结果
10 '''
11 ('A', 'A')
12 ('A', 'B')
13 ('A', 'C')
14 ('A', 'D')
15 ('B', 'A')
16 ('B', 'B')
17 ('B', 'C')
18 ('B', 'D')
19 ('C', 'A')
20 ('C', 'B')
21 ('C', 'C')
22 ('C', 'D')
23 ('D', 'A')
24 ('D', 'B')
25 ('D', 'C')
26 ('D', 'D')
27 '''
28 
29 
30 for i in (x for x in product(range(3), repeat=3)):
31     print(i)
32 
33 # 输出结果
34 '''
35 (0, 0, 0)
36 (0, 0, 1)
37 (0, 0, 2)
38 (0, 1, 0)
39 (0, 1, 1)
40 (0, 1, 2)
41 (0, 2, 0)
42 (0, 2, 1)
43 (0, 2, 2)
44 (1, 0, 0)
45 (1, 0, 1)
46 (1, 0, 2)
47 (1, 1, 0)
48 (1, 1, 1)
49 (1, 1, 2)
50 (1, 2, 0)
51 (1, 2, 1)
52 (1, 2, 2)
53 (2, 0, 0)
54 (2, 0, 1)
55 (2, 0, 2)
56 (2, 1, 0)
57 (2, 1, 1)
58 (2, 1, 2)
59 (2, 2, 0)
60 (2, 2, 1)
61 (2, 2, 2)
62 '''

2.  permutations(iterable, r=None)

在不存在重复元素的情况下生成全排列

例:

 1 from itertools import permutations
 2 for i in (x for x in permutations('ABCD', r=2)):
 3     print(i)
 4 # 输出结果
 5 '''
 6 ('A', 'B')
 7 ('A', 'C')
 8 ('A', 'D')
 9 ('B', 'A')
10 ('B', 'C')
11 ('B', 'D')
12 ('C', 'A')
13 ('C', 'B')
14 ('C', 'D')
15 ('D', 'A')
16 ('D', 'B')
17 ('D', 'C')
18 '''
19 for i in (x for x in permutations(range(3), r=3)):
20     print(i)
21 # 输出结果
22 '''
23 (0, 1, 2)
24 (0, 2, 1)
25 (1, 0, 2)
26 (1, 2, 0)
27 (2, 0, 1)
28 (2, 1, 0)
29 '''

3.    cycle(iterable)

无限循环iterable中的元素

例:

 1 from itertools import cycle
 2 
 3 n = 0
 4 for i in cycle('abcde'):
 5     print(i)
 6     n +=1
 7 
 8     if n >10:
 9         break
10 # 输出结果
11 '''
12 a
13 b
14 c
15 d
16 e
17 a
18 b
19 c
20 d
21 e
22 a
23 '''

4.    islice(iterable, stop)

迭代多少次后停止,stop为迭代次数

例:

 1 from itertools import islice,cycle
 2 for i in islice(cycle('abcde'),5):
 3     print(i)
 4 # 输出结果
 5 '''
 6 a
 7 b
 8 c
 9 d
10 e
11 '''
原文地址:https://www.cnblogs.com/whycai/p/14702246.html