提取列表中Erlang元组

c3frrgcw  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(179)

我得到了列表中的元组:

Contents = [{john, [jill,joe,bob]},
            {jill, [bob,joe,bob]},
            {sue, [jill,jill,jill,bob,jill]},
            {bob, [john]},
            {joe, [sue]}],

我想得到的打印是:

john: [jill,joe,bob]
jill: [bob,joe,bob]
sue: [jill,jill,jill,bob,jill]
bob: [john]
joe: [sue]
xghobddn

xghobddn1#

You can try use lists:foreach/2 or can try implement your own function for iteration and print out lists items:

1> Contents = [{john, [jill,joe,bob]},
{jill, [bob,joe,bob]},
{sue, [jill,jill,jill,bob,jill]},
{bob, [john]},
{joe, [sue]}].
2> lists:foreach(fun({K, V}) -> 
  io:format("~p : ~p~n", [K, V]) 
end, Contents).

Custom function:

% call: print_content(Contents).
print_content([]) ->
  ok;
print_content([{K, V}|T]) ->
  io:format("~p : ~p~n", [K, V]),
  print_content(T).

Lists generators:

1> [io:format("~p : ~p~n", [K, V]) ||  {K, V} <- Contents].
cqoc49vn

cqoc49vn2#

You can simply iterate over the list in whatever way you like, and extract the tuples with pattern matching:

{ Name, ListOfNames } = X

where X is the current item from your list. Then you can print them as desired.

相关问题