如何对值进行perl散列排序并相应地排序键(在两个数组中)? [英] How to sort perl hash on values and order the keys correspondingly (in two arrays maybe)?
本文介绍了如何对值进行perl散列排序并相应地排序键(在两个数组中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Perl中,我想按值排序哈希键,用数字表示:
In Perl, I want to sort the keys of a hash by value, numerically:
{
five => 5
ten => 10
one => 1
four => 4
}
产生两个数组:
producing two arrays:
(1,4,5,10) and (one, four, five, ten)
然后我想规格化values数组,使得数字是连续的:
And then I want to normalize the values array such that the numbers are sequential:
(1,2,3,4)
我该怎么做?
推荐答案
首先按关联值对键进行排序。然后获取值(例如,通过使用散列片)。
First sort the keys by the associated value. Then get the values (e.g. by using a hash slice).
my @keys = sort { $h{$a} <=> $h{$b} } keys(%h);
my @vals = @h{@keys};
或者如果你有一个散列引用
Or if you have a hash reference.
my @keys = sort { $h->{$a} <=> $h->{$b} } keys(%$h);
my @vals = @{$h}{@keys};
这篇关于如何对值进行perl散列排序并相应地排序键(在两个数组中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文