Python提供了直接的方法来查找序列的排列和组合。这些方法位于itertools软件包中。
首先导入itertools包以在Python实现permutations方法。此方法将一个列表作为输入,并返回一个元组的对象列表,其中包含所有以列表形式排列的元组。
# A Python program to print all
# permutations using library function
from itertools import permutations
# Get all permutations of [1, 2, 3]
perm = permutations([1, 2, 3])
# Print the obtained permutations
for i in list(perm):
print (i)
输出:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
它产生n!如果输入序列的长度为n,则进行排列。
如果要获取长度为L的排列,则以这种方式实现。
# A Python program to print all
# permutations of given length
from itertools import permutations
# Get all permutations of length 2
# and length 2
perm = permutations([1, 2, 3], 2)
# Print the obtained permutations
for i in list(perm):
print (i)
输出:
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
它生成nCr * r!输入序列的长度为n并且输入参数为r时进行排列。
此方法将一个列表和一个输入r作为输入,并返回一个元组的对象列表,该元组包含以列表形式包含长度r的所有可能组合。
# A Python program to print all
# combinations of given length
from itertools import combinations
# Get all combinations of [1, 2, 3]
# and length 2
comb = combinations([1, 2, 3], 2)
# Print the obtained combinations
for i in list(comb):
print (i)
输出:
(1, 2)
(1, 3)
(2, 3)
- 组合以输入的字典顺序排序。因此,如果输入列表已排序,则将按排序顺序生成组合元组。
# A Python program to print all # combinations of a given length from itertools import combinations # Get all combinations of [1, 2, 3] # and length 2 comb = combinations([1, 2, 3], 2) # Print the obtained combinations for i in list(comb): print (i)
输出:
(2, 1) (2, 3) (1, 3)
- 元素根据其位置而不是其价值被视为唯一。因此,如果输入元素是唯一的,则每个组合中都不会有重复值。
# A Python program to print all combinations # of given length with unsorted input. from itertools import combinations # Get all combinations of [2, 1, 3] # and length 2 comb = combinations([2, 1, 3], 2) # Print the obtained combinations for i in list(comb): print (i)
输出:
(1, 1) (1, 3) (1, 3)
- 如果我们想将相同元素组合为相同元素,则可以使用combinations_with_replacement。
# A Python program to print all combinations # with an element-to-itself combination is # also included from itertools import combinations_with_replacement # Get all combinations of [1, 2, 3] and length 2 comb = combinations_with_replacement([1, 2, 3], 2) # Print the obtained combinations for i in list(comb): print (i)
输出:
(1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)