从Python中的字母枚举所有长度为K的可能字符串 [英] enumerating all possible strings of length K from an alphabet in Python
问题描述
可能重复:
有没有最好的方法来生成所有可能的三个字母的关键字
如何从字母L枚举所有长度为K的字符串,其中L只是一个字符列表?例如。如果 L = ['A','B','C']
和 K = 2
,我会希望枚举所有可能由字母'A'
,'B'
组成的长度为2的字符串, C
。它们可以重复使用,因此'AA'
是有效的。
how can I enumerate all strings of length K from an alphabet L, where L is simply a list of characters? E.g. if L = ['A', 'B', 'C']
and K = 2
, I'd like to enumerate all possible strings of length 2 that can be made up with the letters 'A'
, 'B'
, 'C'
. They can be reused, so 'AA'
is valid.
从本质上讲,这是置换的置换我明白。如果对此有一个更正确的技术术语,请让我知道...。您可以通过从字母L中选择任何字母,并可能以对订单(因此, AB
与 BA
并不相同。)是否存在更清晰的陈述方式?
This is essentially permutations with replacement, as far as I understand. if theres a more correct technical term for this, please let me know.... its essentially all strings of length K that you can make by choosing ANY letter from the alphabet L, and possibly reusing letters, in a way that is sensitive to order (so AB
is NOT identical to BA
according to this.) is there a clearer way to state this?
无论如何我相信解决方案是:
in any case i believe the solution is:
[ ''.join(x) for x in product(L, repeat=K) ]
但是我很感兴趣在其他答案中,尤其是天真的方法与快速的Python方法,以及对速度注意事项的讨论。
but i am interested in other answers to this, esp. naive approaches versus fast Pythonic ones, and discussions of speed considerations.
推荐答案
这是 Python文档
EDIT2:当然正确的答案是产品,谢谢您的评论
of course the right answer is the product, thanks for the comment
print [''.join(x) for x in product('ABC', repeat=3)]
打印27个元素
['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB',
'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA',
'CBB', 'CBC', 'CCA', 'CCB', 'CCC']
这篇关于从Python中的字母枚举所有长度为K的可能字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!