[英]Trasform list in tuple in Elixir
I have a list like this 我有这样的清单
[%{User: "1"}, %{User: "2"}]
After use 使用后
HTTPoison.request(method, url, body, headers, option)
Where headers is 标头在哪里
\"headers\":[{\"User\":\"1\"},{\"User_2\":\"2\"}]\r\n}
I'd like to have a structure like this 我想要一个这样的结构
[{:user, "1"},{:user, "2"},{"content-type", "application/json"}]
And add even 甚至加
{"content-type", "application/json"}
But I don't understand how can I trasform my data(user) in tuple 但是我不明白如何在元组中转换数据(用户)
It is not very clear what exactly you want to transform and how. 还不清楚您到底要转换什么以及如何转换。
Suppose you are want to transform [%{User: "1"}, %{User: "2"}]
into [{user: "1"},{user: "2"}]
. 假设您要将
[%{User: "1"}, %{User: "2"}]
转换为[{user: "1"},{user: "2"}]
。
[%{User: "1"}, %{User: "2"}]
|> Enum.map(fn(item) -> {:user, item[:User]} end)
Will produce 会产生
[user: "1", user: "2"]
And the result is equal to [{:user, "1"},{:user, "2"}]
(keyword list). 结果等于
[{:user, "1"},{:user, "2"}]
(关键字列表)。
Using the Kernel.SpecialForms.for/1
comprehension: 使用
Kernel.SpecialForms.for/1
理解:
for %{User: id} <- [%{User: "1"}, %{User: "2"}], do: {:user, id}
#⇒ [user: "1", user: "2"]
Please note, that [user: "1", user: "2"]
and [{:user, "1"}, {:user, "2"}]
are exactly equivalent . 请注意,
[user: "1", user: "2"]
和[{:user, "1"}, {:user, "2"}]
是完全等效的 。 That said, both represent the same list of tuples (of size 2.) 也就是说,两者都代表相同的元组列表(大小为2)。
To add a new tuple: just add it to the list: 要添加新的元组:只需将其添加到列表中:
[
{"content-type", "application/json"} |
(for %{User: id} <- [%{User: "1"}, %{User: "2"}], do: {:user, id})
]
#⇒ [{"content-type", "application/json"},
# {:user, "1"},
# {:user, "2"}]
or, to the end (expect performance hits when appending elements to the end of a list, it's always better to prepend as shown above and List.reverse/1
afterwards): 或者,最后(预期将元素附加到列表的末尾会影响性能,最好像上面所示先添加,然后再添加
List.reverse/1
):
users = for %{User: id} <- [%{User: "1"}, %{User: "2"}],
do: {:user, id}
users ++ [{"content-type", "application/json"}]
To convert maps to respective keyword lists (tuples of size 2), use Enum.flat_map/2
: 要将地图转换为相应的关键字列表(大小为2的元组),请使用
Enum.flat_map/2
:
[%{foo: "1"}, %{baz: "2"}, %{bix: "3"}]
|> Enum.flat_map(&Map.to_list/1)
#⇒ [foo: "1", baz: "2", bix: "3"]
To get keys as strings: 要将键作为字符串获取:
[%{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"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.