You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Elixir中的元组列表转换为Map?

将元组列表转换为Elixir Map的解决方案

你手头的元组列表每个元素都是{键, 值Map}的结构,要转成以元组首元素为键的Map,Enum.map/2确实只返回列表,满足不了需求,用下面两个方法就能搞定:

方法1:使用Enum.into/2

Enum.into/2可以把可枚举对象的内容注入到目标结构里,这里直接把元组列表注入空Map即可:

tuple_list = [
  {'key1', %{'a' => 9543243, 'b' => 677, 'c' => 733}},
  {'key2', %{'a' => 543, 'b' => 778, 'c' => 222}}
]

result_map = Enum.into(tuple_list, %{})

方法2:使用Map.new/1

Map.new/1专门用来从{键, 值}形式的可枚举对象创建Map,写法更简洁直观:

result_map = Map.new(tuple_list)

这两种方法都会输出你想要的Map结构:

%{
  'key1' => %{'a' => 9543243, 'b' => 677, 'c' => 733},
  'key2' => %{'a' => 543, 'b' => 778, 'c' => 222}
}

内容的提问来源于stack exchange,提问作者Marco C. Stewart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:40:46