【问题标题】:How to get list elements by index in elixir如何在 elixir 中按索引获取列表元素
【发布时间】:2015-12-26 12:48:22
【问题描述】:
{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

我在读取 /etc/hosts 文件并尝试使用 String.split 逐行拆分它时具有以下长生不老药功能。

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

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 文档并在 Google 上搜索了如何在特定索引处获取列表元素。 我知道有head/tail,但必须有更好的方法来获取列表元素。

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

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

【问题讨论】:

  • 你不想在{status, body} = File.read("/etc/hosts")后面跟着if。首选模式匹配:case File.read("/etc/hosts") do {:ok, body} -> ...
  • 好的,很高兴知道这一点。谢谢朋友。

标签: arrays list elixir


【解决方案1】:

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

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

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

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

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


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

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

【讨论】:

  • 我对这个解决方案有点不满意。难道不能只获得 String.split 返回的 X 部分吗? Enum.at 不适用于 String.split。
  • Enum.at 应该可以正常工作。我将在我的答案中添加一个示例。请记住,如果可以通过其他方式解决,在 Elixir 中使用 Enum.at 是非常不习惯的。
  • 如何从数组中的第二项生成Enum.map(即跳过第一项)?
  • @W.M.我不确定我是否正确理解了您的问题,这似乎与此无关。您可能应该发布一个新问题,其中包含示例输入、预期输出以及您迄今为止尝试过的内容。
  • @W.M.您可以使用[head | tail].= list(如果您还需要第一个元素,头部)或tail = tl(list)(如果您不需要头部)来获取列表的尾部,然后将其映射。跨度>
猜你喜欢
  • 2020-01-20
  • 1970-01-01
  • 2013-12-03
  • 2011-05-05
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 2015-01-05
相关资源
最近更新 更多