perl - 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
什么都不做。我在哪里犯了错误以及如何以正确的列顺序实现上述排序?
解决方案
我正在阅读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])
推荐阅读
- json - Elm 'Json.Decode.succeed':如果它应该总是返回相同的值,它是如何在解码管道中使用的?
- unix - Jenkins 用于在不同环境中同步文件夹
- javascript - 在 React 中安装组件后将对象数组与另一个数组对象组合
- java - Spring Boot 无法运行 data.sql 来初始化 DB
- ruby - 如何在 Sequel 中更新对象而不触发任何 before/after/around 钩子
- sqlite - SQLite3 Studio - 错误“无法解析数据库”。
- firebase - DocumentSnapshot 在颤振中返回 null,同时将其作为类的命名参数传递
- python - 在 Amazon EMR 上运行 Python UDF
- fullcalendar - 1 月至 12 月以外的全日历年视图
- python - 在python中拆分没有空格的数字字符串