Elixir:如何检查数组中元组的特定索引中是否存在元素?
Elixir: How do I check if an element exists in a specific index of a tuple in an array?
例如,
[
{1, 3, "1S"},
{3, 3, "3S"},
{9, 3, "9S"},
{10, 3, "10S"},
{11, 3, "11S"},
{12, 3, "12S"},
{13, 3, "13S"}
]
我想检查每个元组的所有第 0 个索引中是否存在 10。是否有内置函数,或者我必须遍历每个 tupe 来检查这个?
elixir in the first place. There are only lists, implemented as Linked Lists中没有数组。
元组不能迭代,只能进行模式匹配、转换为列表或直接使用Kernel.elem/2
访问。
无论你想检查所有个元素,你都要遍历所有元素,即使你有一个数组。
也就是说,有一个 Enum.all?/2
函数,它仍然会在后台迭代列表,但表示法会更简单。
input =
[
{1, 3, "1S"},
{10, 3, "10S"}
]
Enum.all?(input, &match?({10, _, _}, &1))
#⇒ false
Enum.all?(input, &match?({_, 3, _}, &1))
#⇒ true
# or, with elem/2
Enum.all?(input, &elem(&1, 0) == 10)
#⇒ false
Enum.all?(input, &elem(&1, 1) == 3)
#⇒ true
您可以使用 :lists.keymember/3
。它需要三个参数:
- 您要查找的元素
- 要在元组中查找的位置(基于 1)
- 元组列表
iex(1)> x = [
...(1)> {1, 3, "1S"},
...(1)> {3, 3, "3S"},
...(1)> {9, 3, "9S"},
...(1)> {10, 3, "10S"},
...(1)> {11, 3, "11S"},
...(1)> {12, 3, "12S"},
...(1)> {13, 3, "13S"}
...(1)> ]
[
{1, 3, "1S"},
{3, 3, "3S"},
{9, 3, "9S"},
{10, 3, "10S"},
{11, 3, "11S"},
{12, 3, "12S"},
{13, 3, "13S"}
]
iex(2)> :lists.keymember(10, 1, x)
true
iex(3)> :lists.keymember(8, 1, x)
false
iex(4)> :lists.keymember("1S", 3, x)
true
iex(5)> :lists.keymember("2S", 3, x)
false
例如,
[
{1, 3, "1S"},
{3, 3, "3S"},
{9, 3, "9S"},
{10, 3, "10S"},
{11, 3, "11S"},
{12, 3, "12S"},
{13, 3, "13S"}
]
我想检查每个元组的所有第 0 个索引中是否存在 10。是否有内置函数,或者我必须遍历每个 tupe 来检查这个?
elixir in the first place. There are only lists, implemented as Linked Lists中没有数组。
元组不能迭代,只能进行模式匹配、转换为列表或直接使用Kernel.elem/2
访问。
无论你想检查所有个元素,你都要遍历所有元素,即使你有一个数组。
也就是说,有一个 Enum.all?/2
函数,它仍然会在后台迭代列表,但表示法会更简单。
input =
[
{1, 3, "1S"},
{10, 3, "10S"}
]
Enum.all?(input, &match?({10, _, _}, &1))
#⇒ false
Enum.all?(input, &match?({_, 3, _}, &1))
#⇒ true
# or, with elem/2
Enum.all?(input, &elem(&1, 0) == 10)
#⇒ false
Enum.all?(input, &elem(&1, 1) == 3)
#⇒ true
您可以使用 :lists.keymember/3
。它需要三个参数:
- 您要查找的元素
- 要在元组中查找的位置(基于 1)
- 元组列表
iex(1)> x = [
...(1)> {1, 3, "1S"},
...(1)> {3, 3, "3S"},
...(1)> {9, 3, "9S"},
...(1)> {10, 3, "10S"},
...(1)> {11, 3, "11S"},
...(1)> {12, 3, "12S"},
...(1)> {13, 3, "13S"}
...(1)> ]
[
{1, 3, "1S"},
{3, 3, "3S"},
{9, 3, "9S"},
{10, 3, "10S"},
{11, 3, "11S"},
{12, 3, "12S"},
{13, 3, "13S"}
]
iex(2)> :lists.keymember(10, 1, x)
true
iex(3)> :lists.keymember(8, 1, x)
false
iex(4)> :lists.keymember("1S", 3, x)
true
iex(5)> :lists.keymember("2S", 3, x)
false