生成所有可能的三个字母字符串的最佳方法是什么?

2024-05-23 17:52:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在生成所有可能的三个字母关键字e.g. aaa, aab, aac.... zzy, zzz下面是我的代码:

alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

keywords = []
for alpha1 in alphabets:
    for alpha2 in alphabets:
        for alpha3 in alphabets:
            keywords.append(alpha1+alpha2+alpha3)

这一功能能否以更加流畅和高效的方式实现?


Tags: 代码infor字母关键字keywordszzzalpha2
3条回答

您也可以使用map而不是list comprehension(这是map仍然比LC快的情况之一)

>>> from itertools import product
>>> from string import ascii_lowercase
>>> keywords = map(''.join, product(ascii_lowercase, repeat=3))

列表理解的这种变化也比使用''.join更快

>>> keywords = [a+b+c for a,b,c in product(ascii_lowercase, repeat=3)]
from itertools import combinations_with_replacement

alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

for (a,b,c) in combinations_with_replacement(alphabets, 3):
    print a+b+c
keywords = itertools.product(alphabets, repeat = 3)

请参阅documentation for ^{}。如果需要字符串列表,只需使用

keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)]

alphabets也不需要是列表,它可以只是一个字符串,例如:

from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]

如果你只需要lowercase ascii letters就可以了。

相关问题 更多 >