要映射的字符串列表

时间:2020-05-20 12:11:42

标签: elixir

嗨,我要转换从.txt文件中拆分出的这组列表

["a: 1", "b: 2", "c: 3"]

%{"a" => "1", "b" => "2", "c" => "3"}

非常感谢您。

3 个答案:

答案 0 :(得分:1)

for item <- ["a: 1", "b: 2", "c: 3"], into: %{} do
  [k, v] = String.split(item, ": ")
  {k, v}
end
# %{"a" => "1"}, %{"b" => "2"}, %{"c" => "3"}

答案 1 :(得分:1)

最快的方法是使用通用reduce/2

getStuff

或者另一种方式是使用into/2

stuff

答案 2 :(得分:-1)

只是出于好奇:

list = ["a: 1", "a: 2", "a: 3"]

<<?%, ?{, Enum.join(list, ",") :: binary, ?}>>
|> Code.eval_string()
|> elem(0)
#⇒ %{a: 3}

请注意,当输入具有相同键的多个值时,转换为地图必将失败:

Keyword

这就是为什么最好将输入转换为Keyword

通常,应该修改产生此奇怪输入的代码,而不是首先返回// Select body, append SVG area to it, and set the dimensions var svg = d3.select("body") .append("svg") .attr("height", svgHeight) .attr("width", svgWidth); // Append a group to the SVG area and shift ('translate') it to the right and to the bottom var chartGroup = svg.append("g") .attr("transform", `translate(${chartMargin.left}, ${chartMargin.top})`); // Load data from hours-of-tv-watched.csv d3.csv("hours-of-tv-watched.csv").then(function(tvData) { console.log(tvData); // Cast the hours value to a number for each piece of tvData tvData.forEach(function(d) { d.hours = +d.hours; });