组合
import itertoolsnums = [1, 2, 3, 4, 5, 6, 7, 8]for i in itertools.combinations(nums, 4): print(i)(1, 2, 3, 4)(1, 2, 3, 5)(1, 2, 3, 6)(1, 2, 3, 7)(1, 2, 3, 8)。。。(4, 5, 6, 8)(4, 5, 7, 8)(4, 6, 7, 8)(5, 6, 7, 8)
排列
for i in itertools.permutations(nums, 4): print(i)(1, 2, 3, 4)(1, 2, 3, 5)(1, 2, 3, 6)(1, 2, 3, 7)。。。(8, 7, 6, 2)(8, 7, 6, 3)(8, 7, 6, 4)(8, 7, 6, 5)
product
从给定的序列中各取一个生成序列,可重复的排列数
product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...
for i in itertools.product([0, 1], repeat=3): print(i)(0, 0, 0)(0, 0, 1)(0, 1, 0)(0, 1, 1)(1, 0, 0)(1, 0, 1)(1, 1, 0)(1, 1, 1)
combinations_with_replacement
combinations_with_replacement(iterable, r) --> combinations_with_replacement objectReturn successive r-length combinations of elements in the iterableallowing individual elements to have successive repeats.combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
可重复的组合数
for i in itertools.combinations_with_replacement([1, 2, 3, 4], 3): print(i)(1, 1, 1)(1, 1, 2)(1, 1, 3)(1, 1, 4)(1, 2, 2)(1, 2, 3)(1, 2, 4)(1, 3, 3)(1, 3, 4)(1, 4, 4)(2, 2, 2)(2, 2, 3)(2, 2, 4)(2, 3, 3)(2, 3, 4)(2, 4, 4)(3, 3, 3)(3, 3, 4)(3, 4, 4)(4, 4, 4)
对比product
for i in itertools.product([1, 2, 3, 4], repeat=3): print(i)(1, 1, 1)(1, 1, 2)(1, 1, 3)(1, 1, 4)(1, 2, 1)(1, 2, 2)(1, 2, 3)(1, 2, 4)(1, 3, 1)(1, 3, 2)(1, 3, 3)(1, 3, 4)(1, 4, 1)(1, 4, 2)(1, 4, 3)(1, 4, 4)(2, 1, 1)(2, 1, 2)(2, 1, 3)(2, 1, 4)(2, 2, 1)(2, 2, 2)(2, 2, 3)(2, 2, 4)(2, 3, 1)(2, 3, 2)(2, 3, 3)(2, 3, 4)(2, 4, 1)(2, 4, 2)(2, 4, 3)(2, 4, 4)(3, 1, 1)(3, 1, 2)(3, 1, 3)(3, 1, 4)(3, 2, 1)(3, 2, 2)(3, 2, 3)(3, 2, 4)(3, 3, 1)(3, 3, 2)(3, 3, 3)(3, 3, 4)(3, 4, 1)(3, 4, 2)(3, 4, 3)(3, 4, 4)(4, 1, 1)(4, 1, 2)(4, 1, 3)(4, 1, 4)(4, 2, 1)(4, 2, 2)(4, 2, 3)(4, 2, 4)(4, 3, 1)(4, 3, 2)(4, 3, 3)(4, 3, 4)(4, 4, 1)(4, 4, 2)(4, 4, 3)(4, 4, 4)