我怎样才能保持Perl中的排序的散列?

编程入门 行业动态 更新时间:2024-10-26 19:38:03
本文介绍了我怎样才能保持Perl中的排序的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 @aoh =( { 3 => 15, 4 => 8, 5 => 9, }, { 3 => 11, 4 => 25, 5 => 6, }, { 3 => 5, 4 => 18, 5 => 5, }, { 0 => 16, 1 => 11, 2 => 7, }, { 0 => 21, 1 => 13, 2 => 31, }, { 0 => 11, 1 => 14, 2 => 31, }, );

我要在基于价值观相反的顺序排列每个数组索引的哈希值。

I want the hashes in each array index sorted in reverse order based on values..

@sorted = {排序请...........填补这一..........} @aoh;

@sorted = sort { ........... please fill this..........} @aoh;

期望的输出

@aoh =( { 4 => 8, 5 => 9, 3 => 15, }, { 5 => 6, 3 => 11, 4 => 25, }, { 5 => 5, 3 => 5, 4 => 18, }, { 2 => 7, 1 => 11, 0 => 16, }, { 1 => 13, 0 => 21, 2 => 31, }, { 0 => 11, 1 => 14, 2 => 31, }, );

请帮助..在此先感谢..再次说明我的要求:我只希望在每个数组索引哈希值由值进行排序..我不希望要排序的数组。

Please help.. Thanks in advance.. Stating my request again: I only want the hashes in each array index to be sorted by values.. i dont want the array to be sorted..

推荐答案

Perl的哈希值没有秩序。您必须将它们切换到阵列,或(当你需要遍历散列例如)在他们使用排序。

Perl hashes do not have order. You must either switch them to arrays, or sort them upon usage (e.g. when you need to iterate over that hash).

第一种解决方案可能看起来像:

The first solution could look like:

@aoh =( [{ 4 => 8 } , { 5 => 9 }, , { 3 => 15 } ],

...

第二个解决方案是:

foreach $subhash (@aoh) { foreach $sorted_key (sort { $subhash->{$a} <=> $subhash->{$b} } keys %$subhash) { # Do something with $subhash->{$sorted_key}; } }

更多推荐

我怎样才能保持Perl中的排序的散列?

本文发布于:2023-06-10 05:45:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/608240.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Perl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!