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)
"""
本文介绍了Python内置库itertools中的combinations和permutations函数,这两个函数分别用于生成数组中元素的所有组合和排列。通过示例展示了如何使用这两个函数,输出组合与排列的结果,帮助理解它们在数组操作中的应用。
907

被折叠的 条评论
为什么被折叠?



