简体   繁体   中英

Iterate through three lists multiple times sequentially picking one element from a list in each iteration

I want to iterate through each of the three lists sequentially picking one element from each list in every iteration.

subjects=["Americans","Indians"]
verbs=["plays","watch"]
objects=["Baseball","cricket"]
for i,j,k in zip(subjects,verbs,objects):
    print(i,j,k)

The above code gives the output as follows:

Americans plays Baseball

Indians watch cricket

But the intended output is:

Americans play Baseball.

Americans play Cricket.

Americans watch Baseball.

Americans watch Cricket.

Indians play Baseball.

Indians play Cricket.

Indians watch Baseball.

Indians watch Cricket.

Use itertools.product to get all the possible combinations and then print them

>>> subjects=["Americans","Indians"]
>>> verbs=["plays","watch"]
>>> objects=["Baseball","cricket"]
>>> 
>>> from itertools import product
>>> for x in product(subjects,verbs,objects):
...     print('{} {} {}'.format(*x))
... 
Americans plays Baseball
Americans plays cricket
Americans watch Baseball
Americans watch cricket
Indians plays Baseball
Indians plays cricket
Indians watch Baseball
Indians watch cricket

You can iterate as such for the solution:

subjects=["Americans","Indians"] 
verbs=["plays","watch"] 
objects=["Baseball","cricket"]


for s in subjects:
    for v in verbs:
        for o in objects:
            print(s,v,o+".")

itertools.product is the best solution for this, but if you don't want to import a module, the next most efficient solution would be a generator expression.

subjects = ["Americans", "Indians"]
verbs = ["play", "watch"]
objects = ["Baseball", "Cricket"]

# paragraph = "\n".join(f"{s} {v} {o}." for s in subjects for v in verbs for o in objects)  # Alternative single-liner
for sentence in (f"{s} {v} {o}." for s in subjects for v in verbs for o in objects):
    print(sentence)

Output

Americans play Baseball.
Americans play Cricket.
Americans watch Baseball.
Americans watch Cricket.
Indians play Baseball.
Indians play Cricket.
Indians watch Baseball.
Indians watch Cricket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM