-1

我有一个哈希值,其中的值都是数字的。我可以使用 sort 命令对哈希值进行排序,或者按从前到后的顺序对哈希值进行排序,但是如果我想对结果进行加权而不是仅仅按照指定键的顺序呢?有没有办法做到这一点?

编辑:好的,这是代码......

my @check_order = ["disk_usage","num_dbs","qps_avg"];
my %weights     = ( disk_usage => .7,
                    num_dbs    => .4,
                    qps_avg    => .2
);
my @dbs=sort { 
    ($stats{$a}->{$check_order[0]}*$weights{$check_order[0]}) <=>
    ($stats{$b}->{$check_order[0]}*$weights{$check_order[0]})  or
    ($stats{$a}->{$check_order[1]}*$weights{$check_order[1]}) <=> 
    ($stats{$b}->{$check_order[1]}*$weights{$check_order[1]}) or
    ($stats{$a}->{$check_order[2]}*$weights{$check_order[2]}) <=> 
    ($stats{$b}->{$check_order[2]}*$weights{$check_order[2]})
} keys(%stats);
4

2 回答 2

1

您想根据每个元素的函数值对列表进行排序。sort所以在你的陈述中使用一个函数。

@sorted = sub { sort_function($a) <=> sort_function($b) } @unsorted;

sub sort_function {
    my ($input) = @_;

    return $input->{disk_usage} * 0.7 
         + $input->{num_dbs} * 0.4 
         + $input->{qps_avg} * 0.2;

    # -or- more generally

    my $value = 0;
    while (my ($key,$weight) = each %weights) {
        $value += $input->{$key} * $weight;
    }
    return $value;
}

当您的排序功能很昂贵并且要排序的项目很多时,Schwartzian 变换可以提高排序的性能:

@sorted = map { $_->[0] }
          sort { $a->[1] <=> $b->[1] }
          map { [ $_, sort_function($_) ] } 
          @unsorted;
于 2013-07-01T16:05:50.313 回答
0

If your weights are stored in another hash %property This will sort hash keys based on the product $hash{key} * $property{key}

#!/usr/bin/perl
use strict;
use warnings;

my %hash = (
  a => 51,
  b => 61,
  c => 71,
);

my %property = ( a => 7, b => 6, c => 5 );


foreach (sort { ($hash{$a}*$property{$a}) <=> 
                ($hash{$b}*$property{$b}) } keys %hash)
{
    printf("[%d][%d][%d]\n",
    $hash{$_},$property{$_},$hash{$_}*$property{$_});
}
于 2013-07-01T14:11:45.807 回答