[英]Filter single item from a List
Given: 鉴于:
iex(9)> list_of_maps = [%{"a" => 1, "b" => 2, "c" => 3},%{"a" => 66, "b" => 1, "c" => 9},%{"a" => 66, "b" => 20, "c" => 8}]
I can do: 我可以:
iex(10)> Enum.filter(list_of_maps, &(&1["a"] == 1))
Enum.filter(list_of_maps, &(&1["a"] == 1))
[%{"a" => 1, "b" => 2, "c" => 3}]
However now comes the part I dread writing in every language - getting the first value of this list to extract the single item. 但是现在出现了我害怕用每种语言编写的部分-获取此列表的第一个值以提取单个项目。
Is there some standard function in elixir that filters a list, returning single item if there is only one item after a filter is applied, or a list of items if there are numerous items returned after the filter is applied? elixir中是否有一些标准函数来过滤列表,如果在应用过滤器后只有一项,则返回单个项目,或者在应用过滤器后返回许多项,则返回项目列表? Like: 喜欢:
iex(11)> Enum.filterr(list_of_maps, &(&1["a"] == 1))
Enum.filter(list_of_maps, &(&1["a"] == 1))
%{"a" => 1, "b" => 2, "c" => 3}
iex(12)> Enum.filterr(list_of_maps, &(&1["a"] == 66))
Enum.filter(list_of_maps, &(&1["a"] == 66))
[%{"a" => 66, "b" => 1, "c" => 9},%{"a" => 66, "b" => 20, "c" => 8}]]
If you want to filter a list to get only one item , use Enum.find/2
: 如果要过滤列表以仅获取一项 ,请使用Enum.find/2
:
Enum.find(list_of_maps, fn m -> m["a"] == 1 end)
To handle both cases, pattern matching is the way to go: 要处理两种情况,模式匹配是必经之路:
defmodule MyEnum do
def filter(list, fun) do
list
|> Enum.filter(fun)
|> normalize
end
defp normalize([item]), do: item
defp normalize(list), do: list
end
You can then use it like this: 然后可以像这样使用它:
MyEnum.filter(list_of_maps, &(&1["a"] == 1))
It will return a list if there are multiple matches or the map itself if there's only one match. 如果有多个匹配项,它将返回一个列表;如果只有一个匹配项,则将返回地图本身。
Just pipe your filtered list into Enum.at/2
只需将过滤后的列表发送到Enum.at/2
first = list_of_maps |> Enum.filter(&(&1["a"] == 66)) |> Enum.at(0)
That will get the first element of the filtered list regardless of size. 无论大小如何,都将获得过滤列表的第一个元素。
Also, as Dogbert mentioned in the comments you can just use Enum.find/2
instead of filter to just find the first match. 而且,正如Dogbert在评论中提到的那样,您可以只使用Enum.find/2
而不是filter来查找第一个匹配项。
Enum.find(list_of_maps, &(&1["a"] == 66))
Is there some standard function in elixir that filters a list, returning single item if there is only one item … or a list of items if there are numerous items 灵丹妙药中是否有一些标准功能可以过滤列表,如果只有一个…则返回单个项目…或如果有很多项目则返回一个项目列表
No, but pattern matching makes it trivial: 不,但是模式匹配使它变得微不足道:
def single_or_many([single]), do: single
def single_or_many(many), do: many
And if you wanted to treat the empty list specially (before the 'many' case): 而且,如果您想特别对待空列表(在“很多”情况之前):
def single_or_many([]), do: :nil
Then, the function call chain would be: 然后,函数调用链将是:
list_of_maps
|> Enum.filter(&(&1["a"] == 1))
|> single_or_many
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.