2017-10-18 127 views
2

如何在Elixir中使用Enum函數將兩個數組合並在一起?Elixir - 合併2列表列表(如列)

E.g.

points = [[1.0, 2.0], 
       [5.0, 3.0], 
       [2.0, 4.0], 
       [3.0, 1.0], 
       [2.0, 2.0], 
       [4.0, 3.0], 
       [1.0, 2.0], 
       [2.0, 5.0], 
       [14.0, 13.0], 
       [11.0, 12.0], 
       [12.0, 15.0], 
       [32.0, 25.0]] 

    results = [1.0, 
       3.0, 
       2.0, 
       1.0, 
       3.0, 
       2.0, 
       1.0, 
       3.0, 
       2.0, 
       1.0, 
       3.0, 
       2.0] 

的組合陣列(列加),應該是這樣的:

combined = [[1.0, 2.0, 1.0], 
       [5.0, 3.0, 3.0], 
       [2.0, 4.0, 2.0], 
       [3.0, 1.0, 1.0], 
       [2.0, 2.0, 3.0], 
       [4.0, 3.0, 2.0], 
       [1.0, 2.0, 1.0], 
       [2.0, 5.0, 3.0], 
       [14.0, 13.0, 2.0], 
       [11.0, 12.0, 1.0], 
       [12.0, 15.0, 3.0], 
       [32.0, 25.0, 2.0]]  

好像這樣的事情應該工作:

points 
    |> Stream.with_index 
    |> Enum.map(fn({x,i}) -> Enum.into(x, Enum.fetch!(results, i)) end)     

雖然,這將產生一個錯誤:

** (Protocol.UndefinedError) protocol Collectable not implemented for 1.0. This protocol is implemented for: BitString, Ecto.Adapters.SQL.Stream, File.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Plug.Conn, Postgrex.Stream 
    (elixir) lib/collectable.ex:1: Collectable.impl_for!/1 
    (elixir) lib/collectable.ex:77: Collectable.into/1 
    (elixir) lib/enum.ex:1158: Enum.into_protocol/2 
    (elixir) lib/enum.ex:1259: anonymous fn/3 in Enum.map/2 
    (elixir) lib/enum.ex:1824: anonymous fn/3 in Enum.map/2 
    (elixir) lib/stream.ex:1413: anonymous fn/3 in Enumerable.Stream.reduce/3 
    (elixir) lib/stream.ex:978: anonymous fn/3 in Stream.with_index/2 
    (elixir) lib/enum.ex:3161: Enumerable.List.reduce/3 
    (elixir) lib/stream.ex:1433: Enumerable.Stream.do_each/4 
    (elixir) lib/enum.ex:1823: Enum.map/2 

回答

5

每當你想同時遍歷了兩個可枚舉,你應該考慮使用Enum.zip/2。這就是我如何與Enum.zip/2for做到這一點:

for {point, result} <- Enum.zip(points, results) do 
    point ++ [result] 
end 
|> IO.inspect 

輸出:

[[1.0, 2.0, 1.0], [5.0, 3.0, 3.0], [2.0, 4.0, 2.0], [3.0, 1.0, 1.0], 
[2.0, 2.0, 3.0], [4.0, 3.0, 2.0], [1.0, 2.0, 1.0], [2.0, 5.0, 3.0], 
[14.0, 13.0, 2.0], [11.0, 12.0, 1.0], [12.0, 15.0, 3.0], [32.0, 25.0, 2.0]] 

回覆:爲什麼您的代碼不起作用:Enum.into的第二個參數應該是一個枚舉。你可能想將其包裝在一個列表:

Enum.into(x, [Enum.fetch!(results, i)]) 

我建議使用Enum.zip/2解決方案雖然。

+0

太棒了,我真的很喜歡答案 –

0

您可以使用zip從枚舉,如:

resultado=for {point, res} <- Enum.zip(points, results) do 
    point ++ [res] 
    end