我有一个列表,其中包含一个包含一个列表和一个原子的元组。例如:
List = [{[#{aem => "sara",age => "12"},#{aem => "hanna",age => "11"}], blah},
{[#{aem => "han",age => "12"},#{aem => "anna",age => "21"}], blah1}].
我想获取与aem == "sara"
匹配的记录,并在结果中包含元组的第二个元素(在这种情况下为blah
)。
必填结果:{[#{aem =>"sara",age=>"12"], blah}
答案 0 :(得分:2)
1> List = [{[#{aem => "sara",age => "12"},#{aem => "hanna",age => "11"}], blah},
1> {[#{aem => "han",age => "12"},#{aem => "anna",age => "21"}], blah1}].
[{[#{aem => "sara",age => "12"},
#{aem => "hanna",age => "11"}],
blah},
{[#{aem => "han",age => "12"},#{aem => "anna",age => "21"}],
blah1}]
2> [ {L, Y} || {X, Y} <- List, L <- [[M || M<-X, maps:get(aem, M) =:= "sara"]], L =/= []].
[{[#{aem => "sara",age => "12"}],blah}]
答案 1 :(得分:0)
您可以按如下所示拆分第二个列表理解:
-module(foo).
-compile(export_all).
start()->
List = [{[#{aem => "sara",age => "12"},
#{aem => "hanna",age => "11"}], "blah"},
{[#{aem => "han",age => "12"},
#{aem => "anna",age => "21"}], "blah1"}],
listcomp(List).
listcomp([]) -> [];
listcomp([{P, Dir} | T]) ->
case [X || X <- P, maps:get(aem, X) == "sara" ] of
[] -> listcomp(T);
Res -> [{Res, Dir} | listcomp(T)]
end.
答案 2 :(得分:0)
如果您可以假设aem
在某种程度上是唯一的(至少在每个人组中):
[{[Person], Atom} || {People, Atom} <- List, Person = #{aem := "sara"} <- People].
这将产生以下结果:
[{[#{aem => "sara",age => "12"}],blah}]
但是,为了精确匹配预期结果,您只需要从该列表中选择一个元素即可。您可以为此使用hd/1
(如果您知道您将始终拥有至少一个元素,或者不介意崩溃的话,
1> hd([{[Person], Atom} || {People, Atom} <- List, Person = #{aem := "sara"} <- People].
{[#{aem => "sara",age => "12"}],blah}