Elixir中元组中的Trasform列表

时间:2017-09-27 16:08:13

标签: list tuples elixir

我有一个像这样的列表

[%{User: "1"}, %{User: "2"}]

使用后

HTTPoison.request(method, url, body, headers, option)

标题是

\"headers\":[{\"User\":\"1\"},{\"User_2\":\"2\"}]\r\n}

我希望有这样的结构

[{:user, "1"},{:user, "2"},{"content-type", "application/json"}]

添加偶数

{"content-type", "application/json"}

但我不明白如何在元组中转换我的数据(用户)

2 个答案:

答案 0 :(得分:1)

目前还不是很清楚你想要改变什么以及如何改变。

假设您要将[%{User: "1"}, %{User: "2"}]转换为[{user: "1"},{user: "2"}]

[%{User: "1"}, %{User: "2"}]
|> Enum.map(fn(item) -> {:user, item[:User]} end)

将产生

[user: "1", user: "2"]

结果等于[{:user, "1"},{:user, "2"}](关键字列表)。

答案 1 :(得分:1)

使用Kernel.SpecialForms.for/1理解:

for %{User: id} <- [%{User: "1"}, %{User: "2"}], do: {:user, id}
#⇒ [user: "1", user: "2"]

请注意,[user: "1", user: "2"][{:user, "1"}, {:user, "2"}] 完全相同。也就是说,两者都代表相同的元组列表(大小为2)。

添加新元组:只需将其添加到列表中:

[
  {"content-type", "application/json"} |
  (for %{User: id} <- [%{User: "1"}, %{User: "2"}], do: {:user, id})
]
#⇒ [{"content-type", "application/json"},
#   {:user, "1"},
#   {:user, "2"}]

或者,到最后(期望在将元素添加到列表末尾时的性能命中,最好如上所示进行前置,然后再List.reverse/1):

users = for %{User: id} <- [%{User: "1"}, %{User: "2"}],
        do: {:user, id}
users ++ [{"content-type", "application/json"}]

要将地图转换为相应的关键字列表(大小为2的元组),请使用Enum.flat_map/2

[%{foo: "1"}, %{baz: "2"}, %{bix: "3"}]
|> Enum.flat_map(&Map.to_list/1)
#⇒ [foo: "1", baz: "2", bix: "3"]

将密钥作为字符串:

[%{foo: "1"}, %{baz: "2"}, %{bix: "3"}]
|> Enum.flat_map(fn map ->
     for {k, v} <- map, do: {Atom.to_string(k), v}
   end)
#⇒ [{"foo", "1"}, {"baz", "2"}, {"bix", "3"}]