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

问题描述:

我有如下所示如何根据一个数组对多个数组进行排序?

@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回阵列的散列。

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

+0

顺便说一句,我发现其他类似的问题(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

+0

将行转换为列然后排序?例如'[[red 349 fedora],...]'一般的数据结构看起来很难处理。我可能会改变它。 – 2010-10-26 18:37:17

+0

@pst这是我在我的问题中描述的解决方案。 – flies 2010-10-26 18:52:14

这是我用过的一个技巧。

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. 
+2

我认为你最好重新考虑你的数据结构,例如使用散列数组而不是数组散列。但是,如果您必须对分散在多个阵列上的“记录”进行排序,则可以这样做。 – cjm 2010-10-26 18:47:39

+0

我问我的同事谁使用python,这是他的建议,只有在python中,他会使用'argsort'来做到这一点。 – flies 2010-10-26 18:56:48