【问题标题】:Alphabetic list in PythonPython中的字母列表
【发布时间】: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


【解决方案1】:

试试-

a = input('Enter Letter Combination: ') 
check = False
for s in iter_all_strings():
    if s == a:
        check = True

    if check:
        print(s)

    if s == 'cccc':
        break

如果你不想输入,那么只需将 a 的值设置为 - a = 'bbbb'

【讨论】:

  • 感谢您的回复,但这对我没有帮助。 bbbb 和 cccc 只是示例。我已经在 zyWeAZ,因此生成从 a 到 zyWeAZ 的所有内容还需要几个小时才能再次开始生成。
【解决方案2】:

这是你要找的吗?

import itertools

def iter_all_strings():
    for size in itertools.count(1):
        for s in itertools.product(('b','c'), repeat=size):
            yield "".join(s)
        if size == 4:
            break;

for s in iter_all_strings():
    print(s)

这里可以将大小作为输入,字符串作为输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2012-10-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多