elixir - how to get all elements except last in the list?

荒凉一梦 提交于 2019-12-30 16:22:22

问题


Let say I have a list [1, 2, 3, 4]

How can I get all elements from this list except last? So, I'll have [1, 2, 3]


回答1:


Use Enum.drop/2 like this:

list = [1, 2, 3, 4]
Enum.drop list, -1      # [1, 2, 3]



回答2:


My solution (I think it's not a clean, but it works!)

a = [1, 2, 3, 4]
[head | tail] = Enum.reverse(a)
Enum.reverse(tail) # [1, 2, 3]



回答3:


Another option besides the list |> Enum.reverse |> tl |> Enum.reverse mentioned before is Erlang's :lists.droplast function which is slower according to the documentation but creates less garbage because it doesn't create two new lists. Depending on your use case that might be an interesting one to use.




回答4:


If you're looking to get both the last item and the rest of the list preceding it you can now use List.pop_at/3:

{last, rest} = List.pop_at([1, 2, 3], -1)
{3, [1, 2]}

https://hexdocs.pm/elixir/List.html#pop_at/3




回答5:


Another option, though not elegant, would be -

list = [1, 2, 3, 4]
Enum.take(list, Enum.count(list) -1 )   # [1, 2, 3]



回答6:


Erlang

List = [1,2,3,4,5],
NewList = DropLast(List).

DropLast(List) while length(List) > 0 and is_list(List) ->
    {NewList, _} = lists:split(OldList, length(OldList)-1),
    NewList.


来源:https://stackoverflow.com/questions/36233133/elixir-how-to-get-all-elements-except-last-in-the-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!