python-全排列
permutations()
itertools.permutations(iterable, r = None)
-
返回由 iterable序列中的元素生成的长度为r的排列,r默认设置为 iterable 的长度
-
如果有相同的元素,不同位置的元素被认为不同
from itertools import *
s = ['b','a','c']
print(permutations(s))
##输出如下:
<itertools.permutations object at 0x0000027B3F9A8EF0>
print(list(permutations(s,2)))
##输出如下:
[('b', 'a'), ('b', 'c'), ('a', 'b'), ('a', 'c'), ('c', 'b'), ('c', 'a')]
正确输出所有结果
print(type(element))
>> <class 'tuple'>
for element in permutations(s):
a = ' '.join(element)
print(a)
>> a b c
a c b
b a c
b c a
c a b
c b a
输出顺序问题
若需要按顺序输出,先将需要全排列的序列排好序
for element in permutations('bac'):
a = ' '.join(element)
print(a)
>> b a c
b c a
a b c
a c b
c b a
c a b
--------------------------------------------
for element in permutations('abc'):
a = ' '.join(element)
print(a)
>> a b c
a c b
b a c
b c a
c a b
c b a
combinations()
适用情况
上面的 permutations()
输出的是排列,且元素的排列是分先后的,但是如果只需要输出组合,不用分先后,有:
itertools.combinations()
from itertools import *
s = ['1','1','3','2']#如果序列s中有相同的字符,若s是用[]表示的数组,那么s中不同位置的元素被认为不同
##若需要s中相同的字符被认为相同:s = {'1','1','3','2'}
for element in combinations(s,2):
a=''.join(element)
print(a)
>> 11
13
12
13
12
32