Arrays Perl:在哈希数组中查找最大值和最小值
我的Perl结构如下:Arrays Perl:在哈希数组中查找最大值和最小值,arrays,perl,sorting,hash,Arrays,Perl,Sorting,Hash,我的Perl结构如下: #!/usr/bin/perl use strict; use warnings; my %hash = ( 'firstitem' => { '1' => ["A","99"], '2' => ["B","88"], '3' => ["C","77"], }, 'seconditem' => { '3' => ["C","100"],
#!/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
}
}
foreach my$k1(键%hash){
我的$second_hash_ref=$hash{$k1};
my@sorted_k2=排序{$a$b}键%{$second_hash_ref};
每个我的$i(0..$#排序的#k3){
#冒泡排序还是其他排序
}
}
是一个核心模块,提供min
和max
功能:
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
你就快到了
一旦你到了第二级,你需要的是完整的数字列表,以便能够找到该批次的最大值和最小值。因为您需要子键中所有数组的极值,所以不需要迭代第二级键
此外,您可以获取所有数组内容,除非该数字保证位于特定位置。然后使用grep
with筛选出不是数字的元素
最后,对键进行排序没有任何好处
use warnings;
use strict;
use feature 'say';
use Scalar::Util 'looks_like_number';
use List::MoreUtils 'minmax';
my %hash = (
'firstitem' => {
'1' => ["A","99"], '2' => ["B","88"], '3' => ["C","77"],
},
'seconditem' => {
'3' => ["C","100"], '4' => ["D","200"], '5' => ["E","300"],
},
);
foreach my $k1 (keys %hash)
{
my @nums =
grep { looks_like_number($_) }
map { @{ $hash{$k1}{$_} } }
keys %{$hash{$k1}};
my ($min, $max) = minmax @nums;
say "$k1: max = $max, min = $min";
}
这将打印预期值。如果您的实际散列完全如图所示,您可以通过值%{$hash{$k1}}
直接提取arrayrefs,并使用映射{@$}
取消对它们的引用
因为您需要两个极端,所以一个很好的匹配是minmax
from,这是作业的“最有效的可能算法”。该算法的性能在模块的XS版本中完全实现,而Perl版本有一些开销
还要注意核心模块,其中单个
min
和max
以及其他实用程序 我尝试先对第二个键进行排序,然后根据排序后的键迭代值,然后在for循环中进行冒泡排序。Posted可能是@MattJacob的副本我在谷歌上搜索了一下这个问题,发现了一些类似的问题。但我的数据结构有点不同。谢谢你的回答。太棒了。这是一个很好的解决方案。最好知道grep
和Scalar::Util::looks_like_number。感谢您的快速响应。列表::MoreUtils提供了minmax
,这比同时调用min
和max
更有效@MattJacob我可以显式编写什么而不是使用$\u->[1]
?@Luke我不明白这个问题。@MattJaco您在for循环中使用了$\u->[1]
。我知道它调用数组中的元素。我只是想学习其他的称呼方式?像更显式的方式而不是$\u->[1]
@Luke一样,还有什么比数组引用位置1处的元素更显式的呢?