根据第二个数组的元素对数组进行排序

时间:2013-05-06 11:17:46

标签: arrays perl sorting data-structures perl-data-structures

假设我有两个看起来像这样的数组:

('1', '6', '8', '4', '5')
('a', 'c', 'd', 'f', 'w')

我想对第一个数组进行排序,第二个数组中元素的顺序应该与第一个数组的顺序相同,所以二者的顺序如下:

('1', '4', '5', '6', '8')
('a', 'f', 'w', 'c', 'd')

在Perl中如何做到这一点的任何想法?

3 个答案:

答案 0 :(得分:10)

您需要将 indices 排序到数组中。喜欢这个

use strict;
use warnings;

my @aa = qw/ 1 6 8 4 5 /;
my @bb = qw/ a c d f w /;

my @idx = sort { $aa[$a] <=> $aa[$b] } 0 .. $#aa;

@aa = @aa[@idx];
@bb = @bb[@idx];

print "@aa\n";
print "@bb\n";

<强>输出

1 4 5 6 8
a f w c d

答案 1 :(得分:3)

你可以使用哈希。使用第一个数组中的值作为从第二个数组中获取的值的键。然后做一个foreach my $key ( sort keys %the_hash) { do stuff }。如果键值不唯一,则使用数组散列并将值推送到散列中。

#! perl 
use strict;
use warnings;

my @key_data = ('1', '6', '8', '4', '5', '4', '5');
my @val_data = ('a', 'c', 'd', 'f', 'w', 'z', 'w');

my %the_hash;

for ( my $ii=0; $ii<=$#key_data; $ii++) {
    push @{$the_hash{$key_data[$ii]}}, $val_data[$ii];
}

for my $key ( sort keys %the_hash ) {
    print "key $key\n";
    foreach my $val ( @{$the_hash{$key}} ) {
        print "        $val\n";
    }
}

答案 2 :(得分:2)

鲍罗丁的答案是对你的问题的一个极好的和最好的回应。我确实发现数据的结构表明哈希可能是有用的,所以这里有一个通过哈希关联数据并以这种方式排序的例子。

use strict;
use warnings;
use List::MoreUtils qw(mesh);

my @aa = qw/ 1 6 8 4 5 /;
my @bb = qw/ a c d f w /;

my %x = mesh @aa, @bb;
print join(" ", sort keys %x), "\n";
print join(" ", @x{sort keys %x}), "\n";
相关问题