1. 程式人生 > >python中itertools裏的product和permutation

python中itertools裏的product和permutation

bsp 解析 code itertools 有序 list perm 問題 class

python中itertools裏的product和permutation
平時經常碰到全排列或者在n個數組中每個數組選一個值組成的所有序列等等問題,可以用permutation和product解決,很方便,所以在此mark一下吧

直接上代碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from
itertools import * if __name__ == __main__: for j in permutations([2,5,6]): print(j) ‘‘‘ (2, 5, 6) (2, 6, 5) (5, 2, 6) (5, 6, 2) (6, 2, 5) (6, 5, 2) ‘‘‘ list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] for i in product(list1,list2,list3):
print(i) ‘‘‘ (1, 4, 7) (1, 4, 8) (1, 4, 9) (1, 5, 7) (1, 5, 8) (1, 5, 9) (1, 6, 7) (1, 6, 8) (1, 6, 9) (2, 4, 7) (2, 4, 8) (2, 4, 9) (2, 5, 7) (2, 5, 8) (2, 5, 9) (2, 6, 7) (2, 6, 8) (2, 6, 9) (3, 4, 7) (3, 4, 8) (3, 4, 9) (3, 5, 7) (3, 5, 8) (3, 5, 9) (3, 6, 7) (3, 6, 8) (3, 6, 9)
‘‘‘ #[list2]*3表示[list2,list2,list2] #最前面的*號表示將[list2,list2,list2]列表解析成獨立的參數 #也就是相當於入參是(list2,list2,list2) for i in product(*[list2]*3): print(i) ‘‘‘ (4, 4, 4) (4, 4, 5) (4, 4, 6) (4, 5, 4) (4, 5, 5) (4, 5, 6) (4, 6, 4) (4, 6, 5) (4, 6, 6) (5, 4, 4) (5, 4, 5) (5, 4, 6) (5, 5, 4) (5, 5, 5) (5, 5, 6) (5, 6, 4) (5, 6, 5) (5, 6, 6) (6, 4, 4) (6, 4, 5) (6, 4, 6) (6, 5, 4) (6, 5, 5) (6, 5, 6) (6, 6, 4) (6, 6, 5) (6, 6, 6)

python中itertools裏的product和permutation