python 数组的排列与组合:combinations 与 permutations

combinations 与 permutations 函数在python 的 itertools 库中,因此在使用前需要 import itertools

combinations 函数的作用就是罗列出所有数组中 n 个元素的组合,并返回一个可迭代对象

permutations 函数的作用就是罗列出所有数组所有的排列形式,并返回一个可迭代对象

例子:

import itertools
a = [1, 2, 3]
b = itertools.combinations(a, 2)  # 含有两个元素的组合
for bi in b:  # 或 print(list(b))
    print(bi)
"""
输出结果:
(1, 2)
(1, 3)
(2, 3)
"""
c = itertools.permutations(a)  # 全排列
for ci in c:  # 或 print(list(c))
    print(ci)
"""
输出结果:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
"""