如何使任意级别的嵌套for循环 [英] How to make arbitrary level of nested for-loop

查看:90
本文介绍了如何使任意级别的嵌套for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以像这样进行两级嵌套循环

I can do a two level nested loop like this

for i1 in 1:n
  for i2 in 1:n
    do something with (i1,i2)      

如何将其扩展到任意级别的嵌套循环?

How do I extend this into arbitrary level of nested loop?

例如,我可以在Python中执行此操作以循环n ^ m的笛卡尔积

For example, I can do this in Python to loop the cartesian product of n^m

for i in (itertools.product(xrange(n),repeat=m)):

喜欢

for i in (itertools.product(xrange(2),repeat=3)):
    print i

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

谢谢@tholy的评论.我已经成功应用了Iterators.jl.我是Julia新手,所以我的代码可能很笨拙.

Thank you for @tholy's comment. I have successfully applied Iterators.jl. I'm a Julia newbie so my code maybe clumsy.

for i in product(repmat(Any[1:2],3)...)
    println(i)
end

(1,1,1)
(2,1,1)
(1,2,1)
(2,2,1)
(1,1,2)
(2,1,2)
(1,2,2)
(2,2,2)

推荐答案

在v0.5中,Base中有一个产品迭代器,因此您现在可以将其编写为Base.product(fill(1:2,3)...). fill产生一个数组,该数组的值重复若干次;我发现这比创建1个元素的数组并调用repmat更为优雅.

In v0.5 there is a product iterator in Base, so you can now write this as Base.product(fill(1:2,3)...). fill produces an array with a value repeated some number of times; I find this a bit more elegant than creating a 1-element array and calling repmat.

这篇关于如何使任意级别的嵌套for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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