2010-10-26 133 views
3

我有如下所示如何根據一個數組對多個數組進行排序?

@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

回答

9

這是我用過的一個技巧。

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

相關問題