如何对 Perl 散列值进行排序并相应地对键进行排序(可能在两个数组中)? [英] How can I sort a Perl hash on values and order the keys correspondingly (in two arrays maybe)?

查看:22
本文介绍了如何对 Perl 散列值进行排序并相应地对键进行排序(可能在两个数组中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中,我想按数值对散列的键进行排序:

In Perl, I want to sort the keys of a hash by value, numerically:

{
  five => 5
  ten => 10
  one => 1
  four => 4
}

生成两个数组:

(1,4,5,10) and (one, four, five, ten)

然后我想规范化值数组,使数字是连续的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆