arrays - Perl:在哈希数组中找到最大值和最小值

我在 Perl 中有以下结构:

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

my %hash = (
    'firstitem' => {
        '1' => ["A","99"],
        '2' => ["B","88"],
        '3' => ["C","77"],
    },
    'seconditem' => {
        '3' => ["C","100"],
        '4' => ["D","200"],
        '5' => ["E","300"],
    },
);

我正在寻找一种方法来查找每个哈希数组中的最大数和最小数。 所以输出将是

firstitem: max:99, min:77
seconditem: max:300, min:100

我的想法是先对二级键进行排序,然后在for循环中进行冒泡排序或其他排序。看起来不是很优雅和聪明。

    foreach my $k1 (keys %hash) {
        my $second_hash_ref = $hash{$k1};                   
        my @sorted_k2 = sort { $a <=> $b } keys %{$second_hash_ref}; 
        foreach my $i (0..$#sorted_k3){ 
            #bubble sort or other sort
        }
    }

最佳答案

List::Util是提供minmax函数的核心模块:

use strict;
use warnings;

use List::Util qw(min max);

my %hash = (
    'firstitem' => {
        '1' => ["A","99"],
        '2' => ["B","88"],
        '3' => ["C","77"],
    },
    'seconditem' => {
        '3' => ["C","100"],
        '4' => ["D","200"],
        '5' => ["E","300"],
    },
);

for my $key (keys(%hash)) {
    my @numbers = map { $_->[1] } values(%{$hash{$key}});
    printf("%s: max: %d, min: %d\n", $key, max(@numbers), min(@numbers));
}

输出:

firstitem: max: 99, min: 77
seconditem: max: 300, min: 100

https://stackoverflow.com/questions/46534911/

相关文章:

php - 使用 Laravel 5.2 集合中的列名获取唯一值的计数

php - 删除 wordpress 站点中超过 2 年的帖子

node.js - 在 Node.js 中生成唯一 ID 的最佳方法是什么?

r - 在 R 中制作特定的分位数图

wpf - 字符串格式正值和负值以及条件颜色格式 XAML

julia - 为什么 Julia 闭包不复制数组?

python - AWS Lambda 压缩文件命令

amazon-web-services - 如何在不使用 AutoScaling 的情况下使用 aw

sql - Oracle SQL - 从给定的字符串形成一个虚拟表以与另一个表连接

Python 2.7 - 如何检查是否按下了 SHIFT-Key 或 CTRL+Key?