1

I have read a file in to a list, the format of the file for example is:

 blue
 yellow
 green
 red

and now i want to find the location (index) of item "green" if done correctly the result would be "3" as it is the 3rd item in the list.

maybe I'm not good at searching google but I couldn't find a solution anywhere :/ so the whole idea of this is:

if (item.exists(List, "green")) {
    index = indexOf(List, "green")
}

First i must know if it exists before I get the index of it. Also I'm trying to do this without having to make any new functions that I would have to call.

thanks for any help

4

1 回答 1

2

一种方法是使用拉链在列表中系上数字:

L = [blue, yellow, green, red],
case lists:keyfind(green, 1, lists:zip(L, lists:seq(1, length(L))) of
  false -> not_there;
  {green, Idx} -> {found, Idx}
end,
...

(未测试)

问题是你想要一个索引。我们很少(如果有的话)在 erlang 程序中使用索引。相反,我们可能会将列表表示为一个集合:

Set = sets:from_list(L),
case sets:is_element(green, Set) of
   true -> ...;
   false -> ...
end,
于 2013-01-24T00:03:04.887 回答