如何将多个for循环组合成一个生成器python

时间:2016-03-28 17:49:44

标签: python for-loop iterator

我正在使用这个for循环的Python项目

for year in yearsindex:
    for month in monthindex:
        for hour in hourindex:
            for node in nodeindex:
                dosomething(year, month, hour, node)

我想知道是否有办法将所有迭代器组合到一个迭代器中以便更具可读性

形式的东西
for (year, month, hour, node) in combinediterator:
    dosomething(year, month, hour, node)

2 个答案:

答案 0 :(得分:4)

这是itertools.product

import itertools
for year, month, hour, node in itertools.product(
        yearsindex, monthindex, hourindex, nodeindex):
    dosomething(year, month, hour, node)

您可以看到,将所有内容填充到单个逻辑行上并不能提高可读性。有几种方法可以使其得到改进。例如,如果你可以避免解包迭代器给你的元组,或者你可以将参数放到列表中itertools.product并用*args解压缩它们:

for arg_tuple in itertools.product(*indexes):
    dosomething(*arg_tuple)

如果循环体长于dosomething的一行,您还可以获得减少缩进的好处。使用短循环体,这并不重要。

答案 1 :(得分:1)

为什么不将它以生成器的形式包装在函数定义中,如下所示:

>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>>
>>> 
>>> def comb_gen(a,b,c):
        for x in a:
            for y in b:
                for z in c:
                    yield (x,y,z)


>>> 
>>> for x,y,z in comb_gen(l1,l2,l3):
        print(x,y,z)


1 4 7
1 4 8
1 4 9
1 5 7
1 5 8
1 5 9
1 6 7
1 6 8
1 6 9
2 4 7
2 4 8
2 4 9
2 5 7
2 5 8
2 5 9
2 6 7
2 6 8
2 6 9
3 4 7
3 4 8
3 4 9
3 5 7
3 5 8
3 5 9
3 6 7
3 6 8
3 6 9