遍历python中未知数量的嵌套循环 [英] Iterating over an unknown number of nested loops in python

查看:398
本文介绍了遍历python中未知数量的嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数量不定的用户定义列表,每个列表包含单词.例如,可能有三个列表,如下所示:

I have a variable number of user-defined lists, each containing words. For example, there may be three lists like the following:

list1 = ["THE", "A"]
list2 = ["ELEPHANT", "APPLE", "CAR"]
list3 = ["WALKED", "DROVE", "SAT"]

我想要的是遍历每个列表中的每个组合,并根据已知单词的词典检查每个组合,以查看哪些单词分组最类似于词典.这意味着迭代将像:

What I want is to iterate over every combination in each list, checking each against a dictionary of known words, to see which word-groupings are most like the dictionary. That means the iterations would be like:

[
    "THE ELEPHANT WALKED",
    "THE APPLE WALKED",
    "THE CAR WALKED",
    "THE ELEPHANT DROVE",
    "THE APPLE DROVE",
    "THE CAR DROVE",
    # ...
    "A CAR SAT",
]

问题在于可以有任意数量的列表,并且每个列表可以包含可变数量的项目.我知道可以为此使用递归,但是我需要一个没有递归的解决方案.我一直遇到的问题是,列表的数量可能是可变的,否则我只会写:

The problem is that there can be any number of lists, and each list can contain a variable amount of items. I know that recursion could be used for this, but I need a solution without recursion. The problem I keep having is the fact that there can be a variable amount of lists, otherwise I would just write:

for a in list1:
    for b in list2:
        for c in list3:
            ...

但是我不知道在哪里停下来...

But I won't know where to stop...

推荐答案

itertools.product 完全满足您的要求:

itertools.product does exactly what you want:

from itertools import product

lists = [
    ['THE', 'A'],
    ['ELEPHANT', 'APPLE', 'CAR'],
    ['WALKED', 'DROVE', 'SAT']
]

for items in product(*lists):
    print items

这篇关于遍历python中未知数量的嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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