julia double for循环,循环遍历词典

时间:2014-10-05 08:02:50

标签: dictionary julia

我刚刚开始使用Julia。根据我的理解,Julia允许您在一行上声明多个for循环。

例如,这个:

for i = 1:2, j = [-1,-2]
    println((i, j))
end

会导致这个:

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

我现在正在做类似的事情,但在循环字典时。我声明如下:

rename = function(x)
    x["num"] = -x["num"]
    x
end

players1 = [["num" => 1],["num" => 2]]
players2 = map(rename, copy(players1)) # = [["num" => -1],["num" => -2]]

奇怪的是,当我这样做时,对我来说:

for i=players1, j=players2
    println(i, j)
end

为什么我没有得到这个输出?

["num"=>1]["num"=>-1]
["num"=>1]["num"=>-2]
["num"=>2]["num"=>-1]
["num"=>2]["num"=>-2] 

1 个答案:

答案 0 :(得分:2)

阿。在这种情况下,map函数仍需要deepcopy

这段代码似乎确实有用。

rename = function(x)
    x["num"] = -x["num"]
    x
end

players1 = [["num" => 1],["num" => 2]]
players2 = map(rename, deepcopy(players1))

for i=players1, j=players2
    println(i, j)
end