迭代遍历一个集合中元素的所有可能的排列组合,itertools模块提供了三个函数来解决此问题。

itertools.permutations

itertools.permutations接收一个集合并产生一个元组序列,每个元组由集合中所有元素的一个可能排列组成。

  1. from itertools import permutations
  2. items = ["a", "b", "c"]
  3. for tup in permutations(items):
  4. print(tup) # ('a', 'b', 'c')\n ('a', 'c', 'b')\n ('b', 'a', 'c')...
  5. # 若想得到指定长度的所有组合情况,可传递一个可选长度参数
  6. for tup in permutations(items, 2):
  7. print(tup) # ('a', 'b')\n ('a', 'c')\n ('b', 'a')...

itertools.combinations

对于itertools.combinations来说,元素顺序不再重要。即("a", "b")("b", "a")最终只会输出一个。

  1. from itertools import combinations
  2. items = ["a", "b", "c"]
  3. # 返回长度为3的元组
  4. for tup in combinations(items, 3):
  5. print(tup) # ('a', 'b', 'c')
  6. # 返回长度为2的元组
  7. for tup in combinations(items, 2):
  8. print(tup) # ('a', 'b')\n ('a', 'c')\n ('b', 'c')

itertools.combinations_with_replacement

itertools.combinations_with_replacement允许同一个元素生成的元组中出现多次。

  1. from itertools import combinations_with_replacement
  2. items = ["a", "b", "c"]
  3. # 返回长度为3的元组
  4. for tup in combinations_with_replacement(items, 3):
  5. print(tup) # ('a', 'a', 'a')\n ('a', 'a', 'b')\n ('a', 'a', 'c')...
  6. # 返回长度为2的元组
  7. for tup in combinations_with_replacement(items, 2):
  8. print(tup) # ('a', 'a')\n ('a', 'b')\n ('a', 'c')...