如何根据一个数组对多个数组进行排序?
问题描述:
我有如下所示如何根据一个数组对多个数组进行排序?
@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.
顺便说一句,我发现其他类似的问题(http://stackoverflow.com/questions/762399/sort-by-value-hash-of-hash-of-hashes-perl http://stackoverflow.com/ question/827105/how-can-i-sort-perl-hashes-which-values-are-array-references),但我不认为这是一回事。 – flies 2010-10-26 18:36:51
将行转换为列然后排序?例如'[[red 349 fedora],...]'一般的数据结构看起来很难处理。我可能会改变它。 – 2010-10-26 18:37:17
@pst这是我在我的问题中描述的解决方案。 – flies 2010-10-26 18:52:14