Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 如何根据一个数组对多个数组进行排序?_Perl_Sorting_Data Structures - Fatal编程技术网

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

Perl 如何根据一个数组对多个数组进行排序?,perl,sorting,data-structures,Perl,Sorting,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); 我想根据其中一个数组的值对其进行排序,以保持并行数组元素的关联。也就是说,如果我交换$hash{nu

我有一个如下的数据结构

@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]
,我想对散列中的所有其他数组进行相同的交换。在这种情况下,如果我对{$a$b}进行排序,则

$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}}数组
,然后将
@sorted code>@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.
my@permutation=sort{$numbers[$a]$numbers[$b]}(0..$#numbers);
@颜色=@颜色[@排列];
@数字=@数字[@排列];
@hats=@hats[@permutation];
#不需要更改%hash,因为它引用了上述数组。

顺便说一句,我发现了其他类似的问题(),但我认为这不是一回事。将行转换为列,然后排序?e、 g.
[[red 349 fedora],…]
一般的数据结构看起来很难处理。我可能会改变它。@ PST,这是我在我的问题中描述的解决方案。不过,你可能想考虑这两个选择中的困难。这是一个有点复杂的问题,你选择提问的事实表明了这一点。但是,如果要在传递时将它们存储为哈希数组,则只需执行以下操作:map{$\>{hat}}@data。这似乎要简单得多。我认为您最好重新考虑您的数据结构,例如,使用散列数组而不是散列数组。但是,如果必须在多个数组中分割“记录”进行排序,这是一种方法。我问我的同事谁使用python,这是他的建议,只有在python中,他才会使用
argsort
进行排序。