perl - 如何根据一个数组对多个数组进行排序?

标签 perl sorting data-structures

我有如下的数据结构

@colors = qw(red blond green);
@numbers = qw(349 1234.5678 3.14159265);
@hats = qw(fedora porkpie bowler);
my %hash = (colors => \@colors, numbers => \@numbers, hats => \@hats);

我想根据其中一个数组的值对它进行排序,保持并行数组元素的关联。也就是说,如果我交换 $hash{numbers}[2]和索引 $hash{numbers}[3] ,我想对哈希中的所有其他数组进行相同的交换。在这种情况下,如果我 sort {$a <=> $b}numbers :

$sorted{numbers} = [3.14159265, 349, 1234.5678];
$sorted{colors}  = ["green", "red", "blond"];
$sorted{hats}  = ["bowler", "fedora", "porkpie"];

我现在使用的解决方案反转了 %hash 的结构放入一个数组,其中 $array[$i]{$k} == $hash{$k}[$i] , 是否 @sorted = sort {$a->{numbers} <=> $b->{numbers}} @array , 然后转换 @sorted从哈希数组返回到数组哈希。

我并不关心排序是否稳定,我只是想知道是否有更好的方法来做到这一点。

最佳答案

这是我用过的一个技巧。

my @permutation = sort { $numbers[$a] <=> $numbers[$b] } (0..$#numbers);
@colors = @colors[@permutation];
@numbers = @numbers[@permutation];
@hats = @hats[@permutation];
# No change to %hash needed, since it has references to above arrays.

关于perl - 如何根据一个数组对多个数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4026805/

相关文章:

multithreading - perl线程异常退出

algorithm - 求第 k 个非自由数

c - dfs 迭代和 dfs 递归的不同输出

perl - 如何通过 sudo (或作为另一个用户)打开 Perl 文件句柄写入数据

perl - 如何在 Mojo::Log 中显示当前用户的信息

perl - 集合格式 : multi not working with Perl Mojolicious Swagger2

string - 对每个长度为 n 的 n 个字符串进行排序的最快方法是什么?

java - 删除自定义对象的 ArrayList 中的重复项

sorting - 删除只有一个变量不同的观察结果

c++ - 在程序中使用同一类的两个不同堆栈时出现段错误