Itertools 等效于嵌套循环“for x in xs: for y in ys...”

Posted

技术标签:

【中文标题】Itertools 等效于嵌套循环“for x in xs: for y in ys...”【英文标题】:Itertools equivalent of nested loop "for x in xs: for y in ys..." 【发布时间】:2014-03-18 07:38:49 【问题描述】:

我有一个嵌套循环来创建一组共轭动词中的所有组合。目的是获得动词、人称和时态的所有可能组合,例如[['to be', 'first person singular', 'future'],['to be', 'second person singular', 'future'], ...]

for v in verbs:
    for p in persons:
        for t in tenses:
            return [v, p, t]

有没有办法减少嵌套,也许使用itertools

【问题讨论】:

相关:Equivalent Nested Loop Structure with Itertools 【参考方案1】:
for v, p, t in itertools.product(verbs, persons, tenses):
    ...

【讨论】:

【参考方案2】:

您可以使用itertools.product 执行此任务:

输入迭代的笛卡尔积。等效于生成器表达式中的嵌套 for 循环。例如,product(A, B) 返回的结果与 ((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)

替代方案是列表理解表达式:

for p in [(x,y,z) for x in a for y in b for z in c]:
    print(p)

【讨论】:

以上是关于Itertools 等效于嵌套循环“for x in xs: for y in ys...”的主要内容,如果未能解决你的问题,请参考以下文章

使用 Itertools 具有内部中断的可变级别的嵌套循环

python中的多个嵌套循环等效替换

python 在itertools中使用product方法来避免嵌套for循环

用itertools.product简化嵌套for循环

算法:用itertools.product()简化嵌套for循环

您如何在方案中运行等效的嵌套 for 循环