生成所有可能的三个字母字符串的最佳方法是什么? [英] What is the best way to generate all possible three letter strings?

查看:46
本文介绍了生成所有可能的三个字母字符串的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am generating all possible three letters keywords e.g. aaa, aab, aac.... zzy, zzz below is my code:

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)

能否以更时尚、更高效的方式实现此功能?

Can this functionality be achieved in a more sleek and efficient way?

推荐答案

keywords = itertools.product(alphabets, repeat = 3)

请参阅文档itertools.product.如果您需要字符串列表,只需使用

See the documentation for itertools.product. If you need a list of strings, just use

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

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

alphabets also doesn't need to be a list, it can just be a string, for example:

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

如果您只需要 小写 ascii 字母,就可以使用.

will work if you just want the lowercase ascii letters.

这篇关于生成所有可能的三个字母字符串的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆