如何在Python中压缩嵌套循环

时间:2018-11-19 04:55:08

标签: python python-3.x loops for-loop nested

我有一个2D列表,其中包含不同单词的列表。我有一组12个嵌套的for循环。我需要遍历2D列表中元素的所有可能组合,并对结果进行简单的计算。

最初,我使用itertools.product()函数执行此操作,然后对每个结果列表执行计算,但是itertools.product()调用的结果变得太大,并且内存不足。这意味着我需要在每次迭代后执行计算。

我的代码如下:

for word1 in possible_words[0]:
    for word2 in possible_words[1]:
            for word3 in possible_words[2]:
                    for word4 in possible_words[3]:
                            for word5 in possible_words[4]:
                                    for word6 in possible_words[5]:
                                            for word7 in possible_words[6]:
                                                    for word8 in possible_words[7]:
                                                            for word9 in possible_words[8]:
                                                                    for word10 in possible_words[9]:
                                                                            for word11 in possible_words[10]:
                                                                                    for word12 in possible_words[11]:
                                                                                        result = ' '.join([word1, word2, word3, word4, word5, word6, word7, word8, word9, word10, word11, word12])                                                                                            
                                                                                        if get_address(result) == desired_address:
                                                                                            return result

此代码可以正常工作,并且可以满足我的需求。但是,我想知道是否有一种方法可以以更pythonic的方式将其压缩下来?

1 个答案:

答案 0 :(得分:2)

使用https://www.youtube.com/watch?v=sqDHBH9IjRU,仅遍历迭代器,而不用它构建列表:

from itertools import product

for words in product(*possible_words):
    result = " ".join(words)
    if result == desired_string:
        return result