使用索引对Perl中的列表进行排序以对另一个列表进行排序和索引

Ame*_*ina 1 sorting perl

假设我有一个包含单词的列表,另一个包含与这些单词相关的置信度:

my @list = ("word1", "word2", "word3", "word4");
my @confidences = (0.1, 0.9, 0.3, 0.6);
Run Code Online (Sandbox Code Playgroud)

我想获得第二对列表,其中@list的置信度高于0.4排序顺序的元素及其相应的置信度.我如何在Perl中做到这一点?(即使用用于排序另一个列表的索引列表)

在上面的示例中,输出将是:

my @sorted_and_thresholded_list = ("word2", "word4");
my @sorted_and_thresholded_confidences = (0.9, 0.6);
Run Code Online (Sandbox Code Playgroud)
  • @list中的条目可能不是唯一的(即排序应该是稳定的)
  • 排序应按降序排列.

ike*_*ami 5

处理并行数组时,必须使用索引.

my @sorted_and_thresholded_indexes =
    sort { $confidences[$b] <=> $confidences[$a] }
     grep $confidences[$_] > 0.4,
      0..$#confidences;

my @sorted_and_thresholded_list =
   @list[ @sorted_and_thresholded_indexes ];
my @sorted_and_thresholded_confidences =
   @confidences[ @sorted_and_thresholded_indexes ];
Run Code Online (Sandbox Code Playgroud)