Python中可循环变量的可变数量

Lor*_*ron 5 python nested-loops python-3.x

我试图想出一种方法,用20个字符的字母表生成所有可能的唯一字符串,其中字符串中的顺序无关紧要,字符串的长度可以变化.因此,例如,对于长度为3的字符串,可能串会AAA,AAB,AAC等,但不包括BAACAA.我想出了一种使用方式itertools.product(),但它的计算成本非常高.最简单的方法是使用嵌套的for循环.例如,要生成长度为4的所有字符串:

alphabet = ["A","C","D","E","F","G","H","I","K","L",
            "M","N","P","Q","R","S","T","V","W","Y"]
combos = []
for a in range(len(alphabet)):
    for b in range(a,len(alphabet)):
        for c in range(b,len(alphabet)):
            for d in range(c,len(alphabet)):
                combos.append(alphabet[a] + alphabet[b] + alphabet[c] + alphabet[d])
Run Code Online (Sandbox Code Playgroud)

现在,通过更改for循环的数量,可以轻松地对任何长度字符串进行此操作.鉴于for循环序列本身是可以预测的,有没有办法简化这个代码,而不是if length == 3运行三个for循环并if length == 4运行四个循环?我现在能想到的唯一方法就是一堆if-elif陈述:

if length == 3:
    for a in range(len(alphabet)):
        for b in range(a,len(alphabet)):
            for c in range(b,len(alphabet)):
                combos.append(alphabet[a] + alphabet[b] + alphabet[c])
elif length == 4:
    for a in range(len(alphabet)):
        for b in range(a,len(alphabet)):
            for c in range(b,len(alphabet)):
                for d in range(c,len(alphabet)):
                    combos.append(alphabet[a] + alphabet[b] + alphabet[c] + alphabet[d])
Run Code Online (Sandbox Code Playgroud)

有没有比仅仅覆盖一堆可能的长度值更简单的方法?

DSM*_*DSM 3

IIUC,您可以简单地使用itertools.combinations_with_replacement.

>>> list(map(''.join, combinations_with_replacement(["a","b","c"],2)))
['aa', 'ab', 'ac', 'bb', 'bc', 'cc']
>>> list(map(''.join, combinations_with_replacement(["a","b","c"],3)))
['aaa', 'aab', 'aac', 'abb', 'abc', 'acc', 'bbb', 'bbc', 'bcc', 'ccc']
>>> list(map(''.join, combinations_with_replacement(alphabet,4))) == orig(alphabet)
True
Run Code Online (Sandbox Code Playgroud)

(其中orig只是将您的原始代码包装到函数中)。