小编Lor*_*ron的帖子

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

我试图想出一种方法,用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 == …
Run Code Online (Sandbox Code Playgroud)

python nested-loops python-3.x

5
推荐指数
1
解决办法
272
查看次数

标签 统计

nested-loops ×1

python ×1

python-3.x ×1