如何在elixir中通过索引获取列表元素

时间:2015-09-29 06:34:45

标签: arrays list elixir

{status, body} = File.read("/etc/hosts")
if status == :ok do
    hosts = String.split body, "\n"
    hosts = Enum.map(hosts, fn(host) -> line_to_host(host) end)
else
    IO.puts "error reading: /etc/hosts"
end

我有以下elixir函数,我在其中读取/ etc / hosts文件并尝试使用String.split逐行拆分。

然后我映射主机的行列表并为每个主机调用line_to_host(host)。 line_to_host方法将行拆分为" ",然后我想设置fromto变量:

def line_to_host(line) do
    data = String.split line, " "
    from = elem(data, 0) // doesn't work
    to = elem(data, 1) // doesn't work either
    %Host{from: from, to: to}
end

我查看了stackoverflow,elixir文档并搜索了如何在特定索引处获取列表元素。 我知道有head/tail但是必须有更好的方法来获取列表元素。

elem(list, index)正是我所需要的,但不幸的是它不能与String.split合作。

如何在elixir中按ID获取列表/元组元素

1 个答案:

答案 0 :(得分:30)

您可以使用模式匹配:

[from, to] = String.split line, " "

也许你想添加parts: 2选项,以确保只有两个部分,以防行中有多个空格:

[from, to] = String.split line, " ", parts: 2

还有Enum.at/2,这可以在这里正常工作,但是是单一的。 Enum.at的问题在于,由于Elixir中的列表实现,它需要遍历整个列表到请求的索引,因此对于大型列表来说效率非常低。

编辑:这是Enum.at所请求的示例,但在这种情况下我不会使用它

parts = String.split line, " "
from = Enum.at(parts, 0)
to = Enum.at(parts, 1)
相关问题