我打算输出这个:
columns = ["id","name","col1","col2"]
rows = [10, "foo", "val1", "val2" ]
Enum.zip(columns, rows) |> Enum.into(%{})
=> %{"col1" => "val1", "col2" => "val2", "id" => 10, "name" => "foo"}
但遗憾的是rows
是一个嵌套列表,例如:[[10, "foo", "val1", "val2" ]]
,因此上面的代码会返回:
=> %{"id" => [10, "foo", "val1", "val2"]}
如何访问内部列表的第一个元素?我试过了rows[0]
,但那没用。
答案 0 :(得分:3)
您可以使用核心函数hd/1
columns = ["id","name","col1","col2"]
rows = [[10, "foo", "val1", "val2" ]]
Enum.zip(columns, hd(rows)) |> Enum.into(%{})
%{"col1" => "val1", "col2" => "val2", "id" => 10, "name" => "foo"}
如果您有多行,则可以映射行:
columns = ["id","name","col1","col2"]
rows = [[10, "foo", "val1", "val2"], [20, "bar", "val3", "val4"]]
Enum.map(rows, &(Enum.zip(columns, &1) |> Enum.into(%{})))
[
%{"col1" => "val1", "col2" => "val2", "id" => 10, "name" => "foo"},
%{"col1" => "val3", "col2" => "val4", "id" => 20, "name" => "bar"}
]