> Erlang中文手册 > keytake/3 从元组列表里提取一个元素

lists:keytake/3

从元组列表里提取一个元素

用法:

keytake(Key, N, TupleList1) -> {value, Tuple, TupleList2} | false

内部实现:

-spec keytake(Key, N, TupleList1) -> {value, Tuple, TupleList2} | false when
      Key :: term(),
      N :: pos_integer(),
      TupleList1 :: [tuple()],
      TupleList2 :: [tuple()],
      Tuple :: tuple().

keytake(Key, N, L) when is_integer(N), N > 0 ->
    keytake(Key, N, L, []).

keytake(Key, N, [H|T], L) when element(N, H) == Key ->
    {value, H, lists:reverse(L, T)};
keytake(Key, N, [H|T], L) ->
    keytake(Key, N, T, [H|L]);
keytake(_K, _N, [], _L) -> false.

从元组列表 TupleList 里查找元组的第 N 个值跟 Key 是一样的元素,如果找到这个元素,则把这个元素从列表里提取出来,最后返回被提取的元素和提取后的元组列表

TupleList = [{a, 1}, {b, 2}, {c, 3}, {d, 4}],
lists:keytake(b, 1, TupleList).