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)
"""
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)