生成给定长度的排列 - Python

时间:2016-05-07 06:05:33

标签: python-2.7 permutation cartesian-product

我想生成一个长度为n的给定字母表中的排列列表。 例如,如果n = 3且字母表包含{A,B},则输出应为:AAA,AAB,ABA,BAA,ABB,BAB,BBA,BBB

1 个答案:

答案 0 :(得分:0)

我从所需的输出中猜测您要生成一个字母表的笛卡儿积,其自身重复n次,而不是排列列表。这个公认的itertools.product()棘手的包装将完成这项工作:

>>> import itertools
>>> def nprod(x, n):
...     args = 'x' + (n-1)*', x'
...     return [''.join(z) for z in eval('itertools.product(%s)' % args)]
...
>>> nprod('AB', 3)
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>> nprod(['1', '2', '3'], 2)
['11', '12', '13', '21', '22', '23', '31', '32', '33']

编辑:哦,傻我!我在文档中没有注意到可选的repeat关键字参数:D

>>> [''.join(x) for x in itertools.product('AB', repeat=3)]
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>>> [''.join(x) for x in itertools.product(['1', '2', '3'], repeat=2)]
['11', '12', '13', '21', '22', '23', '31', '32', '33']