将列表转换为元组列表

时间:2018-10-12 14:33:38

标签: elixir

我有一个这样的列表列表:

[
    ["5b71d7e458c37fa04a7ce768", "5b3f77502dfe0deeb8912b42", "1538077790705827"],
     ["5b71d7e458c37fa04a7ce768","5b3f77502dfe0deeb8912b42","1538078530667847"],
     ["5b71d7e458c37fa04a7ce768","5b3f77502dfe0deeb8912b42","1538077778390908"],
     ["5b71d7e458c37fa04a7ce768","5bad45b1e990057961313822","1538082492283531"]
]

我想将其转换为以下列表:

[ 
  {"5b3f77502dfe0deeb8912b42",
   [{"5b71d7e458c37fa04a7ce768","5b3f77502dfe0deeb8912b42", "1538077790705827"},
    {"5b71d7e458c37fa04a7ce768","5b3f77502dfe0deeb8912b42", "1538078530667847"},
    {"5b71d7e458c37fa04a7ce768", "5b3f77502dfe0deeb8912b42" ,"1538077778390908"}
   ]},

{"5bad45b1e990057961313822",
   [{"5b71d7e458c37fa04a7ce768","5bad45b1e990057961313822","1538082492283531"}
   ]}
]

因此,该键将从原始列表的第二个项目中创建元组

[“ 5b71d7e458c37fa04a7ce768”,“ 5b3f77502dfe0deeb8912b42” ,“ 1538077790705827”],

2 个答案:

答案 0 :(得分:4)

首先,y列表的第二个元素。然后,将结果映射值的每个值映射到Enum.group_byList.to_tuple与地图一起使用时,会自动将每个键/值对转换为元组。

Enum.map

输出:

list = [
  ["5b71d7e458c37fa04a7ce768", "5b3f77502dfe0deeb8912b42", "1538077790705827"],
  ["5b71d7e458c37fa04a7ce768", "5b3f77502dfe0deeb8912b42", "1538078530667847"],
  ["5b71d7e458c37fa04a7ce768", "5b3f77502dfe0deeb8912b42", "1538077778390908"],
  ["5b71d7e458c37fa04a7ce768", "5bad45b1e990057961313822", "1538082492283531"]
]

list
|> Enum.group_by(&Enum.at(&1, 1))
|> Enum.map(fn {k, v} -> {k, Enum.map(v, &List.to_tuple/1)} end)
|> IO.inspect

答案 1 :(得分:0)

我将使用地图根据第二个元素索引列表列表,然后使用Enum.map/2List.to_tuple/1对其进行转换。

如果

l = [
    ["5b71d7e458c37fa04a7ce768", "5b3f77502dfe0deeb8912b42", "1538077790705827"],
     ["5b71d7e458c37fa04a7ce768","5b3f77502dfe0deeb8912b42","1538078530667847"],
     ["5b71d7e458c37fa04a7ce768","5b3f77502dfe0deeb8912b42","1538077778390908"],
     ["5b71d7e458c37fa04a7ce768","5bad45b1e990057961313822","1538082492283531"]
]

然后

l
    |> Enum.reduce(%{}, fn [a,b,c], acc -> put_in(acc[b], (acc[b] && acc[b] || []) ++ [[a,b,c]]) end)
    |> Enum.map(fn {a,b} -> {a, Enum.map(b, &List.to_tuple/1)} end)

完成工作。