Enum.split_with 但只使用结果元组的一侧
Enum.split_with but only use one side of result tuple
如何访问 Enum.split_with()
后的第一个列表?
m = Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
// m = {[4, 2, 0], [5, 3, 1]}
我只想通过另一个 Enum.filter()
函数
访问具有 [4,2,0]
和 运行 的列表
类似
m =
Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
|> Enum.filter(fn -> ) //Filter only first list after split
尝试elem(tuple, index)
m = [5, 4, 3, 2, 1, 0]
|> Enum.split_with(fn x -> rem(x, 2) == 0 end)
|> elem(0)
或者,您可以只使用 Enum.filter
m = Enum.filter([5,4,3,2,1,0], fn x -> rem(x, 2) end)
Enum.split_with/2
is to get both the filtered and rejected items. If you only need either the filtered or rejected items, then Enum.filter/2
and Enum.reject/2
点是更好的选择:
iex(1)> Enum.filter([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0)
[4, 2, 0]
iex(2)> Enum.reject([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0)
[5, 3, 1]
也就是说,有两种访问元组元素的标准方法:
- 通过
=
运算符使用模式匹配:
iex(3)> {first, _} = {:a, :b}
{:a, :b}
iex(4)> first
:a
- 如果是管道的一部分,请使用
elem/2
助手:
iex(5)> {:a, :b} |> elem(0)
:a
如何访问 Enum.split_with()
后的第一个列表?
m = Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
// m = {[4, 2, 0], [5, 3, 1]}
我只想通过另一个 Enum.filter()
函数
[4,2,0]
和 运行 的列表
类似
m =
Enum.split_with([5, 4, 3, 2, 1, 0], fn x -> rem(x, 2) == 0 end)
|> Enum.filter(fn -> ) //Filter only first list after split
尝试elem(tuple, index)
m = [5, 4, 3, 2, 1, 0]
|> Enum.split_with(fn x -> rem(x, 2) == 0 end)
|> elem(0)
或者,您可以只使用 Enum.filter
m = Enum.filter([5,4,3,2,1,0], fn x -> rem(x, 2) end)
Enum.split_with/2
is to get both the filtered and rejected items. If you only need either the filtered or rejected items, then Enum.filter/2
and Enum.reject/2
点是更好的选择:
iex(1)> Enum.filter([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0)
[4, 2, 0]
iex(2)> Enum.reject([5, 4, 3, 2, 1, 0], &rem(&1, 2) == 0)
[5, 3, 1]
也就是说,有两种访问元组元素的标准方法:
- 通过
=
运算符使用模式匹配:
iex(3)> {first, _} = {:a, :b}
{:a, :b}
iex(4)> first
:a
- 如果是管道的一部分,请使用
elem/2
助手:
iex(5)> {:a, :b} |> elem(0)
:a