fli*_*ies 3 sorting perl 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);
Run Code Online (Sandbox Code Playgroud)
我想根据其中一个数组的值对其进行排序,保持并行数组元素的关联.也就是说,如果我交换$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"];
Run Code Online (Sandbox Code Playgroud)
我使用现在的溶液反转的结构%hash成一个阵列,其中$array[$i]{$k} == $hash{$k}[$i],确实@sorted = sort {$a->{numbers} <=> $b->{numbers}} @array,然后转换@sorted从散列阵列阵列的散列回来.
我真的不在乎排序是否稳定,我只是想知道是否有更好的方法.
asc*_*ler 10
这是我用过的一个技巧.
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2570 次 |
| 最近记录: |