如何在 Perl 中返回排序列表的索引? [英] How to return a sorted list's index in Perl?
本文介绍了如何在 Perl 中返回排序列表的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比如说,我有一个清单:
Say, I have a list:
@abc = (5,7,6,2,7,1);
我必须获得一个排序列表以及一个排序列表索引.所以输出将是:
I have to obtain a sorted list as well as a sorted list index. So the output will be:
@sorted_list = (7,7,6,5,2,1);
@sorted_list_index = (1,4,2,0,3,5);
我也在寻找一种非常有效的方法来解决这个问题,因为我实际上正在处理一个包含 2^16 个条目的长列表.
I am also looking a very efficient approach for this problem, since I am actually dealing with a long list with 2^16 entries.
推荐答案
如果要对索引进行排序,则需要生成它们
If you want to sort the indexes, you'll need to generate them
0..$#unsorted
然后你像其他任何东西一样对它们进行排序
Then you sort them like anything else
my @sorted_indexes = sort { $unsorted[$b] <=> $unsorted[$a] } 0..$#unsorted;
可以使用切片获取排序后的值.
Grabbing the sorted values can be done using a slice.
my @sorted_values = @unsorted[ @sorted_indexes ];
这篇关于如何在 Perl 中返回排序列表的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文