【问题标题】:Sort list of list erlang列表erlang的排序列表
【发布时间】:2014-02-21 14:04:47
【问题描述】:
PropertyInfo = [
    [{LandNo, Acquisition, Heir, Property, LandTypeCount, LandType}],
    [{LandNo, Acquisition, Heir, Property, LandTypeCount, LandType}],
    [{LandNo, Acquisition, Heir, Property, LandTypeCount, LandType}],
    [{LandNo, Acquisition, Heir, Property, LandTypeCount, LandType}],
]

PropertyInfo 是包含元组中数据库对象的列表列表,其中Heir:code() 将返回一个6 位代码eg. "010011", "00209", ""020011". 如何使用该继承人代码在 erlang 中对该列表进行排序?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    通过使用lists:sort/2 和排序函数:

    manual excerpt:

    排序(Fun, List1) -> List2

    类型:

    Fun = fun((A :: T, B :: T) -> boolean()) 
    List1 = List2 = [T] 
    T => term() 
    

    返回一个包含 List1 已排序元素的列表, 根据排序函数 Fun。 Fun(A, B) 应该返回 true 如果 A 在排序中比较小于或等于 B,则为 false 否则。

    订购乐趣可能如下所示:

    fun([Tuple1],[Tuple2]) ->
        Prop1 = element(3,Tuple1);
        Prop2 = element(3,Tuple2); 
        case {Prop1:code(),Prop2:code()} of
            {Same,Same}   -> true;
            {Code1,Code2} -> SomeComparisonFun(Code1,Code2)
        end
        end
    

    这使您可以提供一个可以比较这些值的函数,一旦您决定了一个指标,让您说出哪个值应该大于其他值。

    【讨论】:

    • 感谢您的回答!
    【解决方案2】:
    SortedList = lists:sort(
                             fun({_, _, A, _, _, _}, {_, _, B, _, _, _}) -> 
                                  A:code() =< B:code() 
                             end, 
                             PropertyInfo).
    

    这很简单,我使用了这个内置的lists:sort() 函数。

    【讨论】:

      猜你喜欢
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 2022-10-18
      相关资源
      最近更新 更多