如何在Python中压缩嵌套循环

格里扎德

我有一个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的方式将其压缩下来?

网波

使用itertools.product,仅遍历迭代器,而不用它构建列表:

from itertools import product

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章