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

2024-05-14 15:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个Python项目中使用这个for循环

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)

Tags: 项目方法innodeforyear形式可读性
2条回答

这是^{}

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的一行长,那么还可以减少缩进。对于一个短环体,这并不重要。你知道吗

为什么不把它以生成器的形式封装在函数定义中,就像这样:

>>> 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

相关问题 更多 >

    热门问题