简体   繁体   English

Elixir:在列表中查找中间项

[英]Elixir: Find middle item in list

I'm trying to learn Elixir. 我正在努力学习Elixir。 In most other languages i've battled with, this would be an easy task. 在我与之斗争的大多数其他语言中,这将是一件容易的事。

However, i can't seem to figure out how to access a list item by index in Elixir, which i need for finding the median item in my list. 但是,我似乎无法弄清楚如何通过Elixir中的索引访问列表项,我需要在列表中找到中间项。 Any clarification would be greatly appreciated! 任何澄清将不胜感激!

You will want to look into Enum.at/3 . 您将需要查看Enum.at/3

a = [1,2,3,4,5]
middle_index = a |> length() |> div(2)
Enum.at(a, middle_index)

Note: This is expensive as it needs to traverse the entire list to find the length of the list, and then traverse halfway through the list to find what the actual element is. 注意:这很昂贵,因为它需要遍历整个列表以查找列表的长度,然后遍历列表中途以查找实际元素的内容。 Generally speaking, if you need random access to an item in a list, you should be looking for a different data structure. 一般来说,如果您需要随机访问列表中的项目,您应该寻找不同的数据结构。

This is how I would do it: 我就是这样做的:

Enum.at(x, div(length(x), 2))

Enum.at/3 retrieves the value at a particular index of an enumerable. Enum.at/3检索可枚举的特定索引处的值。 div/2 is the equivalent of the Python 2.x / integer division. div/2相当于Python 2.x /整数除法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM