如果没有itertools,如何替换itertools.product?

2024-05-14 16:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我目前正在编写一个python脚本。不幸的是,两个模块彼此不工作。然而,我非常需要其中一个(numba),另一个(itertools),我觉得可以更容易地替换

我只需要一些方法来将(3)这样的输入转换成能够输出该长度内所有ascii字母组合的内容(在本例中是从a-aa-ab-ba-…-ZZZ)。输入的数字不必精确地等于字符串长度,但我需要对每个字符串执行一个函数,所以我需要分别使用它们

我尝试了嵌套for循环,但从未达到我想要的结果。 提前谢谢


Tags: 模块方法字符串脚本内容abascii数字
1条回答
网友
1楼 · 发布于 2024-05-14 16:19:12

大部分itertools代码都在文档中。它们也展示了相同或相似的配方https://docs.python.org/3/library/itertools.html?highlight=itertools此处:

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)

现在您已经有了不使用itertools的产品。你可以

import string 
product(string.ascii_letters,list(string.ascii_letters)+[''],list(string.ascii_letters)+[''])

相关问题 更多 >

    热门问题