本文介绍了生成给定长度的排列 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

我从所需的输出中猜测您想要生成一个字母表的 笛卡尔积,其中自身重复 n 次而不是排列列表.这是 itertools.product() 会做的很好:

>>>导入迭代工具>>>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']

I want to generate a list of permutations over a given alphabet of length n.For example, if n = 3 and the alphabet includes {A,B}, output should be: AAA,AAB,ABA,BAA,ABB,BAB,BBA,BBB

解决方案

I'm guessing from the desired output that you want to generate the cartesian product of an alphabet with itself repeated n times rather than a list of permutations. This admittedly tricky wrapper of itertools.product() will do the job just fine:

>>> 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']

EDIT: Oh, silly me!!! I didn't notice in the documentation the optional repeat keyword argument :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']

这篇关于生成给定长度的排列 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 04:52