-4

可能重复:
Perl 按散列中的值对散​​列进行排序

我已经在网上浏览了很多解决方案,但我找不到任何满足我需求的东西。

我有一个大的单词列表,每个单词都附加了值

例子:

my %list = (
  word => 10,
  xword => 15,
  yword => 1
)

该列表一直在继续,但我希望能够返回具有最高对应值的前 5 个哈希元素

4

3 回答 3

2
use strict;
use warnings;

sub topN {
  my ($N, %list) = (shift, @_);
  $N = keys %list if $N > keys %list;
  return (sort { $list{$b} <=> $list{$a} } keys %list)[0..$N-1];
}

my %list = ( word => 10, xword => 15, yword => 1, zword => 4);     
print join (",", topN(5, %list)), "\n";

输出:

xword,word,zword,yword
于 2012-12-07T23:45:19.280 回答
1

这可以满足您的需要。Use of uninitialized value请注意,如果您的散列元素少于五个,它将引发警告,您可能需要添加代码来满足这一要求。它也是低效的,因为它对整个散列进行排序,而不是只查找前五个值。这是否是一个问题取决于你的情况。

use strict;
use warnings;

my %list = (
  word => 10,
  xword => 15,
  yword => 1,
);

my @top5 = (sort { $list{$b} <=> $list{$a} } keys %list)[0..4];

print "$_\n" for @top5;

输出

xword
word
yword
于 2012-12-07T23:48:57.183 回答
0
use strict;
use warnings;

my %list = (
   word => 10,
   xword => 15,
   yword => 1,
);

my @top5 = sort { $list{$b} <=> $list{$a} } keys %list;
splice(@top5, 5) if @top5 > 5;

print "$_\n" for @top5;
于 2012-12-08T01:48:23.087 回答