您可以大大简化循环:def next_code(code):
code = list(code)
for i, let in enumerate(code):
if let != 'z':
code[i] = chr(ord(let) + 1)
break
code[i] = 'a'
return ''.join(code)
如果目标只是逐个生成所有值,从'aaa'开始,itertools.product可用于生成生成器:
^{pr2}$
或者将它设置为一个函数,根据需要调用该函数以获取序列中的下一个代码,而不将其用作迭代器:nextcode = allcodes().__next__ # .next on Py2
如果生成器应该是无限的(因此它从zzz包装到{}),只需将allcodes更改为以下任意一个:# Avoid cycle if storing all 26**3 codes in memory is a bad idea
def allcodes():
while True:
yield from map(''.join, map(reversed, product(string.ascii_lowercase, repeat=3)))
# On Py2, change yield from line to:
# for code in map(''.join, map(reversed, product(string.ascii_lowercase, repeat=3))): yield code
或者使用更高的内存成本但更简单:from itertools import cycle
def allcodes():
return cycle(map(''.join, map(reversed, product(string.ascii_lowercase, repeat=3))))