我是灵药开发的新手.我在elixir中解析字符串时遇到问题.假设我有字符串"来自地狱的Hello World".我知道我可以像这样拆分它String.split("Hello World from the hell").我想知道无论如何要将此字符串的元素分配到elixir中列出?
String.split/1返回一个列表 - 一个Elixir的基本数据结构,以及地图和元组.列表是Elixir的首选基本系列.即使在内部它是链表,您也可以使用Enum模块中的函数对其执行各种操作:
$ iex
iex(1)> ls = String.split("Hello World from the hell")
["Hello", "World", "from", "the", "hell"]
iex(2)> i ls
Term
["Hello", "World", "from", "the", "hell"]
Data type
List
Reference modules
List
iex(3)> Enum.take(ls, 2)
["Hello", "World"]
iex(4)> Enum.at(ls, 4)
"hell"
iex(5)> [l0, l1, l2, l3, l4] = ls
["Hello", "World", "from", "the", "hell"]
iex(6)> l4
"hell"
iex(7)> Enum.take(ls, 4) ++ ["iex", "shell"]
["Hello", "World", "from", "the", "iex", "shell"]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,Enum.at/3它提供了类似于a[i]样式数组访问的东西.
如果你担心在列表中找到一个元素的效率 - 例如你的输入字符串将会比你的输入字符串长得多,"Hello World from the hell"并且你将通过索引多次从它获取元素,基本上每次遍历它,你可以从中构建一个地图,并通过索引有效地查看单词:
iex(8)> with_indices = Enum.with_index(ls)
[{"Hello", 0}, {"World", 1}, {"from", 2}, {"the", 3}, {"hell", 4}]
iex(9)> indices_and_words = Enum.map(with_indices, fn({a, b}) -> {b, a} end)
[{0, "Hello"}, {1, "World"}, {2, "from"}, {3, "the"}, {4, "hell"}]
iex(10)> map = Map.new(indices_and_words)
%{0 => "Hello", 1 => "World", 2 => "from", 3 => "the", 4 => "hell"}
iex(11)> map[0]
"Hello"
iex(12)> map[4]
"hell"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3475 次 |
| 最近记录: |