Python:嵌套计数器 [英] Python: Nesting counters

查看:121
本文介绍了Python:嵌套计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的客户来说,迭代多个计数器正在变成一个经常性的任务。

For my customers, iterating through multiple counters is turning into a recurring task.

最简单的方法是这样的:

The most straightforward way would be something like this:

cntr1 = range(0,2)
cntr2 = range(0,5)
cntr3 = range(0,7)

for li in cntr1:
    for lj in cntr2:
        for lk in cntr3:
            print li, lj, lk

计数器的数量可以从3开始,而嵌套的循环开始占用不动产。

The number of counters can be anywhere from 3 on up and those nested for loops start taking up real estate.

是否有Pythonic方法可以做这样的事情?

Is there a Pythonic way to do something like this?

for li, lj, lk in mysteryfunc(cntr1, cntr2, cntr3):
    print li, lj, lk

我一直在想itertools中的东西适合这个法案,但我对itertools不太熟悉,无法理解这些选项。有没有像itertools这样的解决方案,还是我需要自己动手?

I keep thinking that something in itertools would fit this bill, but I'm just not familiar enough with itertools to make sense of the options. Is there already a solution such as itertools, or do I need to roll my own?

谢谢,
j

推荐答案

你想要的是 itertools.product

for li, lj, lk in itertools.product(cntr1, cntr2, cntr3):
    print li, lj, lk

将完全按照您的要求进行操作。该名称源于笛卡尔积的概念。

Will do exactly what you are requesting. The name derives from the concept of a Cartesian product.

这篇关于Python:嵌套计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆