我有如下的数据结构
@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/