首页 > 解决方案 > perl 根据多列排序(列的顺序很重要)

问题描述

我正在尝试学习按多列对 perl 中的 2D 数组进行排序,以便按指定列的顺序对值进行排序,即首先根据第一列排序,然后根据第二列等。这样桌子:

3  2
5  2
1  4

排序为

1  4
3  2
5  2

如果排序的顺序是第一列、第二列或

3  2
5  2
1  4

如果排序是根据第二列然后是第一列。

但事实证明,我什至无法根据任何列对表格进行排序。

my @a = ([3,1,2], [3,5,4]);
my @b = sort {

    $a->[0] <=> $b->[0]

} @a;
print Dumper \@b

什么都不做。我在哪里犯了错误以及如何以正确的列顺序实现上述排序?

标签: perl

解决方案


我正在阅读my @a = ([3,1,2], [3,5,4]);,因为它有 2 行,每行 3 列。我会存放桌子

3 3
1 5
2 4

my @a = ([3, 3], [1, 5], [2, 4]);相反,这通过使用短路评估使排序更简单

my @a = ([3, 3], [1, 5], [2, 4]);

my @b = sort {
    # Short-circuit evaluation:
    # if the values in the first column aren't equal, return the <=> result for
    # that, otherwise return the <=> result for the second column
    $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1];
} @a;

# @b is now ([1, 5], [2, 4], [3, 3])

推荐阅读