sorting - 按值对哈希进行排序

标签 sorting perl

这不是我填充哈希的方式。为了便于阅读,这里是它的内容,键在一个固定长度的字符串上:

my %country_hash = (
  "001 Sample Name   New Zealand" => "NEW ZEALAND",
  "002 Samp2 Nam2    Zimbabwe   " => "ZIMBABWE",
  "003 SSS NNN       Australia  " => "AUSTRALIA",
  "004 John Sample   Philippines" => "PHILIPPINES,
);

我想获取基于值的排序键。所以我的期望:

"003 SSS NNN       Australia  "
"001 Sample Name   New Zealand"
"004 John Sample   Philippines"
"002 Samp2 Nam2    Zimbabwe   "

我做了什么:

foreach my $line( sort {$country_hash{$a} <=> $country_hash{$b} or $a cmp $b} keys %country_hash ){
  print "$line\n";
}

还有; (我怀疑这会排序但无论如何)

my @sorted = sort { $country_hash{$a} <=> $country_hash{$b} } keys %country_hash;
foreach my $line(@sorted){
  print "$line\n";
}

它们都没有正确排序。我希望有人能提供帮助。

最佳答案

如果您使用了 warnings , 你会被告知 <=>是错误的运算符(operator);它用于数字比较。使用 cmp用于字符串比较。引用sort .

use warnings;
use strict;

my %country_hash = (
  "001 Sample Name   New Zealand" => "NEW ZEALAND",
  "002 Samp2 Nam2    Zimbabwe   " => "ZIMBABWE",
  "003 SSS NNN       Australia  " => "AUSTRALIA",
  "004 John Sample   Philippines" => "PHILIPPINES",
);

my @sorted = sort { $country_hash{$a} cmp $country_hash{$b} } keys %country_hash;
foreach my $line(@sorted){
    print "$line\n";
}

这打印:

003 SSS NNN       Australia  
001 Sample Name   New Zealand
004 John Sample   Philippines
002 Samp2 Nam2    Zimbabwe   

这也有效(没有额外的数组):

foreach my $line (sort {$country_hash{$a} cmp $country_hash{$b}} keys %country_hash) {
    print "$line\n";
}

关于sorting - 按值对哈希进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67233361/

相关文章:

php - PHP/MySQL 中的最新条目按升序排列

python - Pandas :在数据框中重新分配值

algorithm - 稳定排序算法有共同的原因吗?

java - 为什么冒泡排序外循环在n-1处结束?

Perl快速检查重叠间隔?

linux - 不断将 Linux 命令的输出写入文件

python - 我可以在 Django admin 中忽略前导空格对项目进行排序吗?

perl - 如何在 Perl 中获取给定时区的秒数 - UTC 时间

perl - Perl 中是否有 n 叉树实现?

perl - 如何在 Perl 文件中写入当前时间戳?