按值和键对哈希进行排序(按顺序)
我正在寻找一种很好的方法来在 Perl 中先按值排序,然后再按键排序。
示例:
my %userids = (
williams => "Marketing",
smith => "Research",
johnson => "Research",
jones => "Marketing",
brown => "Marketing",
davis => "Research"
);
输出:
Marketing: brown
Marketing: jones
Marketing: williams
Research: davis
Research: johnson
Research: smith
请注意,value 是第一个排序级别。第二个排序级别是键。知道如何以优雅且高性能的方式做到这一点吗?谢谢!
I'm looking for a nice way to sort a hash in Perl by value first and by key afterwards.
Example:
my %userids = (
williams => "Marketing",
smith => "Research",
johnson => "Research",
jones => "Marketing",
brown => "Marketing",
davis => "Research"
);
Output:
Marketing: brown
Marketing: jones
Marketing: williams
Research: davis
Research: johnson
Research: smith
Please note that value was the first sorting level. Second sorting level is key. Any idea how to do this in an elegant and high-performance way? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很好的参考: http://www.misc-perl-info.com/perl-sort.html #shv
Good reference: http://www.misc-perl-info.com/perl-sort.html#shv
我想再添加一件事,在排序中使用
\Lequence
。来自Perlfaq4:如何对哈希进行排序(可以选择按值而不是键)?
为了使我们的报告顺序不区分大小写,我们在双引号字符串中使用
\L 序列
使所有内容都小写。然后,sort()
块会比较小写值以确定键的放置顺序。输出:
2。
输出:
I would like to add one more thing, use
\L sequence
in sorting.From Perlfaq4: How do I sort a hash (optionally by value instead of key)?
To make our report order case-insensitive, we use the
\L sequence
in a double-quoted string to make everything lowercase. Thesort()
block then compares the lowercased values to determine in which order to put the keys.Output :
2.
Output: