2014-10-05 173 views
2

我剛開始使用朱莉婭。據我的理解,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] 

回答

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