gpt4 book ai didi

perl - 基本的 Perl 散列排序键,值,但也键 AND 值

转载 作者:行者123 更新时间:2023-12-01 04:50:23 29 4
gpt4 key购买 nike

好的,我正在编写一个 Perl 程序,它有一个我收集的值的哈希值(完全在一个完全独立的程序中)并提供给这个 Perl 脚本。这个散列是 (string,string) 的散列。

我想通过 3 种方式对值进行排序:首先,我想按键排序。我认为这很容易,您完全按照您的想法进行操作,使用 Perl 的内置排序功能,循环键,并在排序时打印/存储/任何内容。

foreach my $name (sort keys %planets) {
printf "%-8s %s\n", $name, $planets{$name};
}

其次,我想按值排序。同样,这很简单,使用 sort 函数并循环:

foreach my $name (sort { $planets{$a} <=> $planets{$b} } keys %planets) {
printf "%-8s %s\n", $name, $planets{$name};
}

第三,我的问题是,我如何按值排序,但是对于两个键之间的值中的任何关系,我首先排序具有更大的值Asciibetical 键。示例:

Red => 50
Yellow => 75
Blue => 75

is sorted to this, since 'Yellow' is greater asciibetically than 'Blue'
Red 50
Blue 75
Yellow 75

最佳答案

在平局上,比较运算符将返回 0,因此您可以使用 || 链接多个比较:

 sort { $planets{$a} <=> $planets{$b} || $a cmp $b }

关于perl - 基本的 Perl 散列排序键,值,但也键 AND 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27008360/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com