Python:嵌套计数器
对于我的客户来说,迭代多个计数器正在变成一项重复任务。
最直接的方法是这样的:
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 个以上,并且那些嵌套的 for 循环开始占用空间。
有没有Pythonic的方法来做这样的事情?
for li, lj, lk in mysteryfunc(cntr1, cntr2, cntr3):
print li, lj, lk
我一直认为 itertools 中的某些东西符合这个要求,但我只是对 itertools 不够熟悉,无法理解这些选项。是否已有解决方案(例如 itertools),或者我需要推出自己的解决方案?
谢谢, j
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
The number of counters can be anywhere from 3 on up and those nested for loops start taking up real estate.
Is there a Pythonic way to do something like this?
for li, lj, lk in mysteryfunc(cntr1, cntr2, cntr3):
print li, lj, lk
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?
Thanks,
j
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要的是
itertools.product
将完全按照您的要求进行操作。该名称源自笛卡尔积的概念。
What you want is
itertools.product
Will do exactly what you are requesting. The name derives from the concept of a Cartesian product.