组合/合并两个Erlang列表 [英] Combine/Merge Two Erlang lists

查看:173
本文介绍了组合/合并两个Erlang列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在erlang中组合元组列表?我有列表:

How to combine tuple lists in erlang? I have lists:

L1 = [{k1, 10}, {k2, 20}, {k3, 30}, {k4, 20.9}, {k6, "Hello world"}],

L2 = [{k1, 90}, {k2, 210}, {k3, 60}, {k4, 66.9}, {k6, "Hello universe"}],

现在我想要一个组合列表:

now I want a combined list as :

L3 = [
       {k1, [10, 90]},
       {k2, [20, 210]},
       {K3, [30, 60]},
       {k4, [20.9, 66.9]},
       {K6, ["Hello world", "Hello universe"]}
     ].


推荐答案

更短的一些,列表甚至没有拥有相同的密钥,可以无序:

Something shorter, and the lists don't even have to posses the same keys, and can be unordered:

merge(In1,In2) ->
    Combined = In1 ++ In2,
    Fun      = fun(Key) -> {Key,proplists:get_all_values(Key,Combined)} end,
    lists:map(Fun,proplists:get_keys(Combined)).

乐趣可以直接写在列表中:map / 2 函数,但这使它可读。

Fun could be written directly in the lists:map/2 function, but this makes it readable.

输出,数据来自例如:

1> test:merge(L1,L2).
[{k1,"\nZ"},
 {k2,[20,210]},
 {k3,[30,60]},
 {k4,[20.9,66.9]},
 {k6,["Hello world","Hello universe"]}]

\\\
Z
是因为erlang将[10,90]解释为字符串(实际上是列表)。不要打扰。

"\nZ" is because erlang interprets [10,90] as a string (which are, in fact, lists). Don't bother.

这篇关于组合/合并两个Erlang列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆