Python中可预测的for循环的数量可变 [英] Variable number of predictable for loops in Python

查看:304
本文介绍了Python中可预测的for循环的数量可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一种方法,可以从20个字符的字母表生成所有可能的唯一字符串,其中字符串的顺序无关紧要,并且字符串的长度可以变化.因此,例如,对于长度为3的字符串,可能的字符串为AAAAABAAC等,但不包括BAACAA.我想出了一种使用itertools.product()的方法,但是它在计算上非常昂贵.最简单的方法就是使用嵌套的for循环.例如,要生成所有长度为四的字符串:

I am trying to come up with a way to generate all possible unique strings from an alphabet of 20 characters where the order within the string doesn't matter, and the length of the string can vary. So, for instance, for a string of length 3, the possible strings would be AAA, AAB, AAC, etc., but would not include BAA or CAA. I figured out a way using itertools.product(), but it is very computationally expensive. The easiest way to do this is simply using nested for loops. For instance, to generate all strings of length four:

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])

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

Now, this can easily be done for any length string by changing the number of for loops. Given the for loop sequence itself is quite predictable, is there are way to simplify this code instead of having if length == 3 run three for loops and if length == 4 run four loops instead? The only way I can think to do it right now is a bunch of if-elif statements:

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])

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

Is there any easier way than just covering a bunch of possible values of length?

推荐答案

IIUC,您只需使用itertools.combinations_with_replacement.

IIUC, you can simply use 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

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

(where orig is simply your original code wrapped into a function).

这篇关于Python中可预测的for循环的数量可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆