首页 > 代码库 > itertools

itertools

0. Python中引入itertools

1. 笛卡尔积:

 product(iter1, iter2,...,iterN,[repeat=i])

 1 from itertools import product
 2 
 3 #笛卡尔积
 4 #3种常见的iter类型
 5 for x in product(10,repeat=3):
 6     print(x)
 7 for x in product([1,0],repeat=3):
 8     print(x)
 9 for x in product((0,1),repeat=3):
10     print(x)

结果

 

技术分享
 1 (1, 1, 1)
 2 (1, 1, 0)
 3 (1, 0, 1)
 4 (1, 0, 0)
 5 (0, 1, 1)
 6 (0, 1, 0)
 7 (0, 0, 1)
 8 (0, 0, 0)
 9 
10 (1, 1, 1)
11 (1, 1, 0)
12 (1, 0, 1)
13 (1, 0, 0)
14 (0, 1, 1)
15 (0, 1, 0)
16 (0, 0, 1)
17 (0, 0, 0)
18 
19 (0, 0, 0)
20 (0, 0, 1)
21 (0, 1, 0)
22 (0, 1, 1)
23 (1, 0, 0)
24 (1, 0, 1)
25 (1, 1, 0)
26 (1, 1, 1)
View Code

 

复杂示例  

lucky+=[int(‘‘.join([str(y) for y in x])) for x in list(product([4,7],repeat=i))]

 

2.全排列

 permutations(iterable,[,r])

 

1 from itertools import permutations
2 
3 for x in permutations(ABC):
4     print(x)

 结果

(A, B, C)
(A, C, B)
(B, A, C)
(B, C, A)
(C, A, B)
(C, B, A)

 

 

未完待续...

 

itertools