Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何在elixir中通过索引获取列表元素_Arrays_List_Elixir - Fatal编程技术网

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

Arrays 如何在elixir中通过索引获取列表元素,arrays,list,elixir,Arrays,List,Elixir,我有下面的elixir函数,其中我读取/etc/hosts文件,并尝试使用String.split逐行拆分它 然后我映射主机的行列表,并为每个主机调用行到主机(host)。line_to_host方法将行拆分为”,然后我想设置from和to变量: {status, body} = File.read("/etc/hosts") if status == :ok do hosts = String.split body, "\n" hosts = Enum.map(hosts, f

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

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

{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
我浏览了stackoverflow和elixir文档,并在Google上搜索如何在特定索引中获取列表元素。 我知道有头/尾,但必须有更好的方法获取列表元素

elem(list,index)
正是我所需要的,但不幸的是它不能使用
String.split


如何在elixir中按ID获取列表/元组元素可以使用模式匹配:

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
也许您想添加
部分:2
选项,以确保在行中有多个空格的情况下,您只能获得两个部分:

[from, to] = String.split line, " "
还有一种,在这里可以很好地工作,但它是单向的。Enum.at的问题是,由于Elixir中的列表实现,它需要遍历整个列表直到请求的索引,因此对于大型列表来说效率非常低


编辑:这里是请求的带有
Enum.at
的示例,但我不会在本例中使用它


您不想执行
{status,body}=File.read(“/etc/hosts”)
,后面跟
if
。更喜欢模式匹配:
case File.read(“/etc/hosts”)执行{:好的,body}->……
好的,很高兴知道这一点。谢谢,伙计。我对这个解决方案有点不满意。难道不可能只获取该字符串的X部分吗?Enum.at不能与String.split.Enum.at一起使用,应该可以正常工作。我将在我的答案中添加一个例子。请记住,在Elixir中使用Enum.at是非常不明智的,如果可以解决的话。如何从数组中的第二项(即跳过第一项)生成
Enum.map
。@W.M.我不确定我是否正确理解了您的问题,这似乎与此无关。您可能应该发布一个新问题,其中包含示例输入、预期输出和您迄今为止尝试过的内容。@W.M.您可以使用
[head | tail].=list
(如果您还需要第一个元素head)或
tail=tl(list)
(如果您不需要head)来获取列表的尾部,然后映射到它。
[from, to] = String.split line, " ", parts: 2
parts = String.split line, " "
from = Enum.at(parts, 0)
to = Enum.at(parts, 1)