【问题标题】:Sort a list with all three elements of a list, Erlang使用列表的所有三个元素对列表进行排序,Erlang
【发布时间】:2014-06-16 15:38:08
【问题描述】:

我有一个随机排列的结构列表:

L = [[{type1, Str12},{type2, Str22}, {code, Number12}, X],
    [{type1, Str14},{type2, Str24}, {code, Number14}, X],
    [{type1, Str15},{type2, Str25}, {code, Number15}, X],
    [{type1, Str13},{type2, Str23}, {code, Number13}, X],
    [{type1, Str11},{type2, Str21}, {code, Number11}, X],
     ...]    

其中,StrX、NumberX 是变量: 我必须对它进行排序,分别按第一个位置字符串、第二个位置字符串和第三个数字字符串排序。与列表的所有其他剩余元素无关。 例如。让我们说,

L1 = [{type1, "Hello"},{type2, "World"}, {code, "00009"}, "india", 24, ...],
L2 = [{type1, "Alarm"},{type2, "Started"}, {code, "00203"}, "Japan", -, ...],
...etc.

基本上L应该是这样的:

L = [[{type1, Str11},{type2, Str21}, {code, Number11}, X],
    [{type1, Str12},{type2, Str22}, {code, Number12}, X],
    [{type1, Str13},{type2, Str23}, {code, Number13}, X],
    [{type1, Str14},{type2, Str24}, {code, Number14}, X],
    [{type1, Str15},{type2, Str25}, {code, Number15}, X], ...].

对我来说很复杂,但是,我尝试过这样但没有用。

SortedHeirList = lists:sort(fun(A, B) -> 
                    get_type1_val(A) =< get_type1_val(B),
                    get_type2_val(A) =< get_type2_val(B),
                    get_Code(A) =< get_code(B),
               end, L).

【问题讨论】:

    标签: sorting erlang


    【解决方案1】:

    只使用lists:sort/1 不起作用?

    1> L1 = [{type1, "Hello"},{type2, "World"}, {code, "00009"}, "india", 24], L2 = [{type1, "Alarm"},{type2, "Started"}, {code, "00203"}, "Japan"].        
    [{type1,"Alarm"},{type2,"Started"},{code,"00203"},"Japan"]
    2> lists:sort([L1, L2]).
    [[{type1,"Alarm"},{type2,"Started"},{code,"00203"},"Japan"],
     [{type1,"Hello"},{type2,"World"},{code,"00009"},"india",24]]
    

    更多详情请见8.11 Term Comparisons

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 2018-03-08
      相关资源
      最近更新 更多