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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32837195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:09:17  来源:igfitidea点击:

How to get list elements by index in elixir

arrayslistelixir

提问by Pascal Raszyk

{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

I have the following elixir function where I read the /etc/hosts file and try to split it line by line using String.split.

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

Then I map through the line list of hosts and call line_to_host(host) for each. The line_to_host method splits the line by " "and then I want to set the fromand tovariable:

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

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

I looked through stackoverflow, the elixir docs and googled about how to get an list element at a specific index. I know there is head/tailbut there has to be a better way of getting list elements.

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

elem(list, index)does exactly what I need but unfortunately it's not working with String.split.

elem(list, index)完全符合我的需要,但不幸的是它不适用于String.split.

How to get list/tuple elements by ID in elixir

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

回答by Patrick Oscity

You can use pattern matching for that:

您可以为此使用模式匹配:

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

Maybe you want to add parts: 2option to ensure you will get only two parts in case there is more than one space in the line:

也许您想添加parts: 2选项以确保在行中有多个空格的情况下您只会得到两个部分:

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

There is also Enum.at/2, which would work fine here but is unidiomatic. The problem with Enum.atis that due to the list implementation in Elixir, it needs to traverse the entire list up to the requested index so it can be very inefficient for large lists.

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



Edit: here's the requested example with Enum.at, but I would not use it in this case

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

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