Itertools equivalent of nested loop “for x in xs: for y in ys…”

隐身守侯 提交于 2019-11-29 14:46:42
for v, p, t in itertools.product(verbs, persons, tenses):
    ...

You can use itertools.product for this task:

Cartesian product of input iterables. Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
import itertools
for p in itertools.product(a,b,c):
    print(p)

The alternative would be a list comprehension expression:

for p in [(x,y,z) for x in a for y in b for z in c]:
    print(p)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!