如何排序List <list <integer>&gt;基于每个内部列表中元素的顺序?

时间:2017-11-20 21:15:09

标签: sorting

例如,我有一个像

这样的列表
[[0, 5, 9],[0, 3, 5], [0, 3, 7], [0, 5, 7], [0, 3, 9], [0, 7, 9], [3, 5, 7]]

期待的结果应该像

[[0, 3, 5], [0, 3, 7], [0, 3, 9], [0, 5, 7], [0, 5, 9], [0, 7, 9], [3, 5, 7]]

排序基于数组中的每个元素。所以[0,3,9]应该在[0,5,7]之前。

非常感谢任何可能的解决方案!

3 个答案:

答案 0 :(得分:0)

制作一个比较两个列表的比较函数,然后将自定义比较函数传递给您的排序函数。

答案 1 :(得分:0)

我的第一个想法是覆盖比较器并比较列表中的每个元素。

Collections.sort(res, new Comparator<ArrayList<Integer>>() {
        @Override
        public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
            if (o1.size() == o2.size()){
               for (int i = 0; i < o1.size(); i++){
                   if (o1.get(i) < o2.get(i)){
                       return -1;
                   }else{
                       return 1;
                   }
               }
            }
            return o1.size() - o2.size();
        }
    });

然而,它不适用于案例[[0,3,9,] [0,5,7]],因为当我们比较3和5时,[0,3,9]将会去首先,但是当我们比较7和9时,[0,5,7]将首先出现。

所以我尝试比较字符串而不是整数:

Collections.sort(res, new Comparator<ArrayList<Integer>>() {
        @Override
        public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
            if (o1.size() == o2.size()){
                String s1 = "";
                String s2 = "";
               for (int n1: o1){
                   s1 += n1;
               }
               for (int n2: o2){
                   s2 += n2;
               }
               return s1.compareTo(s2);
            }
            return o1.size() - o2.size();

        }
    });

答案 2 :(得分:0)

为什么如此复杂 - 它只是int - 您可以根据重要性将它们乘以10 ^ n并将它们相加。这形成了排序键,然后是整数的简单排序,升序:

(C# - 你没有指定语言)

using System.Linq;
using System.Collections.Generic;
using System;

internal class Program
{
    static void Main(string[] args)
    {
        List<List<int>> l = new List<List<int>> {
            new List<int>{0, 5, 9 },
           new List<int>{0, 3, 5},
           new List<int>{0, 3, 7},
           new List<int>{0, 5, 7},
           new List<int>{0, 3, 9},
           new List<int>{0, 7, 9},
           new List<int>{ 3, 5, 7}
            };

        var sorted = l.OrderBy(sub => sub[0] * 100 + sub[1] * 10 + sub[2]);

        Console.WriteLine("[" + string.Join("],[", sorted.Select(s => string.Join("],[", s))));
        Console.ReadLine();
    }
}

(Python)的

data = [[0, 5, 9],[0, 3, 5], [0, 3, 7], [0, 5, 7], [0, 3, 9], [0, 7, 9], [3, 5, 7]]

sorteddata = sorted(data, key= lambda x: x[0]*100+x[1]*10+x[2])
print (data)
print (sorteddata)

输出:

[[0, 5, 9], [0, 3, 5], [0, 3, 7], [0, 5, 7], [0, 3, 9], [0, 7, 9], [3, 5, 7]] => 
    [[0, 3, 5], [0, 3, 7], [0, 3, 9], [0, 5, 7], [0, 5, 9], [0, 7, 9], [3, 5, 7]]