如何在列表中搜索特定元素

时间:2018-07-02 13:23:36

标签: list erlang

我想检索列表中第一个出现的"Apple"的id(在这种情况下为1)。例如:

List = [["1","Apple"],["2","Orange"],["3","Apple"]].

3 个答案:

答案 0 :(得分:4)

在Erlang世界中,对于固定大小的数据类型,我们使用tuple。您的列表可能会长大,但是我认为它的元素是固定大小的,所以我建议使用元组作为它的元素,并且您可以使用模块listsproplists的API函数:

1> List = [{"1", "Apple"}, {"2", "Orange"}, {"3", "Apple"}].
[{"1","Apple"},{"2","Orange"},{"3","Apple"}]
%% Search in List for a tuple which its 2nd element is "Apple":
2> lists:keyfind("Apple", 2, List).
{"1","Apple"}
3> lists:keyfind("Unknown", 2, List).
false
%% Take first Tuple which its 2nd element is "Apple", Also yield Rest of List:
4> lists:keytake("Apple", 2, List).
{value,{"1","Apple"},[{"2","Orange"},{"3","Apple"}]}
%% Replace a tuple which its 1st element is "3" with {"3", "Banana"}
5> lists:keyreplace("3", 1, List, {"3", "Banana"}).
[{"1","Apple"},{"2","Orange"},{"3","Banana"}]

答案 1 :(得分:1)

您可以使用lists:search/2

List = [["1","Apple"],["2","Orange"],["3","Apple"]],
{value, [Id, "Apple"]} =
  lists:search(fun([Id, Name]) -> Name == "Apple" end, List),
Id.

答案 2 :(得分:0)

您可能正在这里找到一个简单的递归函数。

find_key([], _) -> error;
find_key([[Key, Value] | Rest], Search) when Value = Search -> Key;
find_key([_ | Rest], Search) -> find_key(Rest, Search).