自从我使用Python以来已经有一段时间了,需要做这样的事情。但是我想做的是遍历每个独特的四个字符的字母序列。例如:
aaaa
aaab
...
aaaz
...
abcd
...
zzzz
import string
az = string.ascii_lowercase
for c1 in az:
for c2 in az:
for c3 in az:
for c4 in az:
print(c1 + c2 + c3 + c4)
是否有更有效或更美观的方法?
答案 0 :(得分:1)
我认为您正在寻找itertools.product()
。如果您将其传递给string.ascii_lowercase
和所需的字符数,则其余部分应由它完成:
from itertools import product
import string
[''.join(s) for s in product(string.ascii_lowercase, repeat=4)]
-
['aaaa',
'aaab',
'aaac',
'aaad',
'aaae',
'aaaf',
'aaag',
'aaah',
'aaai',
...
'zzzq',
'zzzr',
'zzzs',
'zzzt',
'zzzu',
'zzzv',
'zzzw',
'zzzx',
'zzzy',
'zzzz']
答案 1 :(得分:0)
如果需要自己滚动,则可以从0
迭代到26⁴ - 1
,然后使用自己的数字转换转换为以26为底的数字。
def baseN(number, base, digits):
return ((number == 0) and digits[0]) or (baseN(number // base, base, digits) + digits[number % base])
digits = "abcdefghijklmnopqrstuvwxyz"
base = len(digits)
length = 4
for number in range(base ** length):
print((digits[0] * (length - 1) + baseN(number, base, digits))[-length:])