Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
961 views
in Technique[技术] by (71.8m points)

list - Iterating over an unknown number of nested loops in 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...