【问题标题】:How to search for a specific element in list如何在列表中搜索特定元素
【发布时间】:2018-12-10 17:53:39
【问题描述】:

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

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

【问题讨论】:

标签: list erlang


【解决方案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】:

    一个简单的递归函数可能就是您在这里寻找的。​​p>

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

    【讨论】:

    • 我认为在 C 中实现 BIF lists:keyfind/2 会更好。
    • @Hynek-Pichi-Vychodil 对于实际系统,我同意。我不知道他们是在为自己写这个作为练习,还是为了在现实世界中使用。我的回答是考虑到练习。
    【解决方案3】:

    在 Erlang 世界中,对于固定大小的数据类型,我们使用 tuples。你的 List 可能会长大,但我认为它的元素是固定大小的,所以我建议对其元素使用元组,你可以使用模块的 API 函数listsproplists

    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"}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多