所以我有一个散列的哈希,看起来像这样:
my %hash = (
'fruits' => {
'apple' => 34,
'orange' => 30,
'pear' => 45,
},
'chocolates' => {
'snickers' => 35,
'lindt' => 20,
'mars' => 15,
},
);
我想只访问数量最多的水果和最大数量的巧克力。输出应该如下:
水果:梨 巧克力:士力架foreach my $item (keys %hash){
#print "$item:\t"; # this is the object name
foreach my $iteminitem (keys %{$hash{$item}})
{
my $longestvalue = (sort {$a<=>$b} values %{$hash{$item}})[-1]; #this stores the longest value
print "the chocolate/fruit corresponding to the longestvalue" ;
#iteminitem will be chocolate/fruit name
}
print "\n";
}
我知道这并不困难,但我正在消隐!
答案 0 :(得分:2)
下面按降序值对每个hashref的键进行排序,因此max是返回的第一个元素:
my %hash = (
chocolates => { lindt => 20, mars => 15, snickers => 35 },
fruits => { apple => 34, orange => 30, pear => 45 },
);
while (my ($key, $hashref) = each %hash) {
my ($max) = sort {$hashref->{$b} <=> $hashref->{$a}} keys %$hashref;
print "$key: $max\n";
}
输出:
fruits: pear
chocolates: snickers
答案 1 :(得分:0)
这是另一种方式:
use strict;
use warnings;
use List::Util qw(max);
my %hash = (
'fruits' => {
'apple' => 34,
'orange' => 30,
'pear' => 45,
},
"chocolates" => {
'snickers' => 35,
'lindt' => 20,
'mars' => 15,
},
);
for (keys %hash) {
my $max = max values %{$hash{$_}}; # Find the max value
my %rev = reverse %{$hash{$_}}; # Reverse the internal hash
print "$_: $rev{$max}\n"; # Print first key and lookup by max value
}
<强>输出:强>
fruits: pear
chocolates: snickers
答案 2 :(得分:0)
为此您可能需要List::UtilsBy
:
use List::UtilsBy 'max_by';
my %hash = (
chocolates => { lindt => 20, mars => 15, snickers => 35 },
fruits => { apple => 34, orange => 30, pear => 45 },
);
foreach my $key ( keys %hash ) {
my $subhash = $hash{$key};
my $maximal = max_by { $subhash->{$_} } keys %$subhash;
print "$key: $maximal\n";
}
对于这个小例子来说,这可能并不重要,但对于更大的案例,这有很大的不同。这将在O(n)
时间内针对散列的大小运行,而&#34;排序并采用第一个索引&#34;解决方案将花费O(n log n)
时间,慢得多,对键列表进行排序,然后扔掉除第一个结果之外的所有内容。