[英]Python Consonant/Vowel Permutations
I want to generate all possible permutations for specific consonant/vowel setups. 我想为特定的辅音/元音设置生成所有可能的排列。 For example, I would like all possible 3 letter word permutations with the format of CVC (Consonant, Vowel, Consonant). 例如,我希望所有可能的3个字母的单词排列都采用CVC格式(辅音,元音,辅音)。
I don't know of any way to multiply permutations: 我不知道增加排列的任何方法:
permutations("bcdfghjklmnpqrstvwxyz",1) * permutations("aeiou",1) * permutations("bcdfghjklmnpqrstvwxyz",1)
How can this be achieved in python? 如何在python中实现?
itertools.product to the rescue: itertools.product的解救:
>>> import itertools
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> vowels = "aeiou"
>>> poss = list(itertools.product(consonants, vowels, consonants))
>>> len(poss)
2205
>>> poss[:10]
[('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'a', 'd'), ('b', 'a', 'f'), ('b', 'a', 'g'), ('b', 'a', 'h'), ('b', 'a', 'j'), ('b', 'a', 'k'), ('b', 'a', 'l'), ('b', 'a', 'm')]
or if you want words specifically: 或者,如果您想要特定的单词:
>>> words = list(''.join(letters) for letters in itertools.product(consonants, vowels, consonants))
>>> words[:10]
['bab', 'bac', 'bad', 'baf', 'bag', 'bah', 'baj', 'bak', 'bal', 'bam']
Here's a non-itertools based solution: 这是一个非基于itertools的解决方案:
>>> import string
>>> vowels = set('aeiou')
>>> consonants = set(string.ascii_lowercase) - vowels
>>> cvc_generator = (''.join((c1, v, c2)) for c1 in consonants for v in vowels for c2 in consonants)
>>> cvc_generator.next()
'cac'
>>> cvc_generator.next()
'cab'
>>> cvc_generator.next()
'cad'
>>> cvc_generator.next()
'cag'
>>> print ' '.join(cvc for cvc in cvc_generator)
caf cah cak caj cam cal can caq cap cas car cat caw cav cay cax caz cic cib cid cig cif cih cik cij cim cil cin ciq cip cis cir cit ciw civ ciy cix ciz cec ceb ced ceg cef ceh cek cej cem cel cen ceq cep ces cer cet cew cev cey cex cez cuc cub cud cug cuf cuh cuk cuj cum cul cun cuq cup cus cur cut cuw cuv cuy cux cuz coc cob <..snip..>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.