Elixir - Merge 2列表列表(如列)

时间:2017-10-18 20:38:27

标签: elixir

如何使用Enum函数在Elixir中将两个数组合并在一起?

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

2 个答案:

答案 0 :(得分:6)

每当你想同时迭代两个枚举时,你应该考虑使用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]]

Re:为什么你的代码不起作用:Enum.into的第二个参数应该是一个可枚举的。您可能希望将其包装在列表中:

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

我建议使用Enum.zip/2解决方案。

答案 1 :(得分:0)

您可以使用Enum的zip,例如:

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