【发布时间】:2021-09-25 09:14:08
【问题描述】:
早上好,我看到this 发布了这个帖子,我提出的问题是如何制作一个脚本/函数来实现所有可能的字母组合。我发现用户 Kevin 的代码非常有用,所以我开始使用它。虽然有时我的代码会停止,它必须重新开始。
我的问题是:如何使用我选择的字符串开始这段代码(见下文)。例如,如果我在某处输入 bbbb,它将生成 bbbb 和 cccc 之间的所有可能组合。
from string import ascii_lowercase
import itertools
def iter_all_strings():
for size in itertools.count(1):
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
for s in iter_all_strings():
print(s)
if s == 'cccc':
break
编辑: 所以我找到了 itertools.product() 的源代码,它是这样的:
def product(*args, repeat=1):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
来源:https://docs.python.org/3/library/itertools.html#itertools.combinations 有谁可以用这段代码实现我的目标?
【问题讨论】:
-
您将需要编写自己的生成器来指定起点。应该不会很难。
标签: python enumerate alphabetical