Python 中是否有一个快捷方式可以解决一长堆嵌套的循环



我正在为我的空闲时间做一个项目,只是试图生成带有线性顺序字符的 12 个字符的大字符串。

为此,我使用了一个由 12 个嵌套for循环组成的野兽。

def linear():
    vocabulary = string.digits + string.ascii_uppercase
    coupon = list("000000000000")
    count = 0
    for a in range(36):
        coupon[0] = vocabulary[a]
        for b in range(36):
            coupon[1] = vocabulary[b]
            for c in range(36):
                coupon[2] = vocabulary[c]
                for d in range(36):
                    coupon[3] = vocabulary[d]
                    for e in range(36):
                        coupon[4] = vocabulary[e]
                        for f in range(36):
                            coupon[5] = vocabulary[f]
                            for g in range(36):
                                coupon[6] = vocabulary[g]
                                for h in range(36):
                                    coupon[7] = vocabulary[h]
                                    for i in range(36):
                                        coupon[8] = vocabulary[i]
                                        for j in range(36):
                                            coupon[9] = vocabulary[j]
                                            for k in range(36):
                                                coupon[10] = vocabulary[k]
                                                for l in range(36):
                                                    coupon[11] = vocabulary[l]
                                                    count += 1
                                                    print(''.join(coupon), "  -  Attempt number: ", count)

它按预期工作,但我想知道 Python 是否可以以一种更漂亮的方式再次让我感到惊讶,这种方式仍然可以让我在生成每个组合时迭代它 - 因为正如其他人指出的那样 - 36^12 组合是不现实的。

让我们看看:

import string, itertools
for a in itertools.product(string.digits + string.ascii_uppercase, repeat=12):
    print(''.join(a))

但我不会尝试运行这个。

Using itertools.combs(iterable, r(:

from itertools import combinations
import string
vocabulary = string.digits + string.ascii_uppercase
output = list(combinations(vocabulary, 12))
output = [('').join(x) for x in output]

但是考虑到有36^12组合可能~4.7383813e+18

最新更新