在阵列的散列排序键由阵列中的元素数 [英] sort keys in hash of array by the number of elements in the array
本文介绍了在阵列的散列排序键由阵列中的元素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有数组的哈希值。
%非洲之角=(
'C1'=> ['1','3','3','3'],
'C2'=> ['3','2'],
'C3'=> ['1','3','3','4','5','5'],
'C4'=> ['3','3','4'],
'C5'=> ['1'],
);
的
数组中的值并不重要本身。我想以降序由阵列的大小键进行排序。输出应该的样子。
C3#这个键包含了最元素的数组
C1
C4
C2
C5#此项包含用最少的元素的数组
我不知道为什么,这是行不通的。
我的foreach $键(排序{$ {非洲之角$ B}< = GT; $非洲之角{$一个}}键%HOA){
打印键$ \\ N的;
}
解决方案
您必须比较数组大小:
FOREACH我的$键(排序{标@ {$非洲之角{$ B}}< =>标@ {$非洲之角{$ A}}}键%HOA){
打印键$ \\ N的;
}
I have a hash of arrays.
%HoA = (
'C1' => ['1', '3', '3', '3'],
'C2' => ['3','2'],
'C3' => ['1','3','3','4','5','5'],
'C4' => ['3','3','4'],
'C5' => ['1'],
);
The values in the array don't matter per se. I would like to sort the keys by the size of the array in descending order. The output should look like.
C3 # this key contains an array with the most elements
C1
C4
C2
C5 # this key contains an array with the least elements
I don't know why this isn't working.
foreach my $key ( sort { $HoA{$b} <=> $HoA{$a}} keys %HoA ) {
print "$key\n";
}
解决方案
You must compare the array sizes:
foreach my $key ( sort { scalar @{$HoA{$b}} <=> scalar @{$HoA{$a}}} keys %HoA ) {
print "$key\n";
}
这篇关于在阵列的散列排序键由阵列中的元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文