python-全排列

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
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值