Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the indices from sorting a list in Perl to sort and index another

Tags:

sorting

perl

Say I have a list that holds words and another one that holds confidences associated with those words:

my @list = ("word1", "word2", "word3", "word4");
my @confidences = (0.1, 0.9, 0.3, 0.6);

I would like to obtain a second pair of lists with the elements of @list whose confidences were higher than 0.4 in sorted order, and their corresponding confidences. How do I do that in Perl? (i.e. use the list of indices used for sorting another list)

In the example above, the output would be:

my @sorted_and_thresholded_list = ("word2", "word4");
my @sorted_and_thresholded_confidences = (0.9, 0.6);
  • The entries in @list may not be unique (i.e. and sorting should be stable)
  • Sorting should be in descending order.
like image 595
Amelio Vazquez-Reina Avatar asked Dec 01 '25 16:12

Amelio Vazquez-Reina


2 Answers

When dealing with parallel arrays, one must work with the indexes.

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 ];
like image 192
ikegami Avatar answered Dec 03 '25 07:12

ikegami


Using List::MoreUtils' pairwise and part:

use List::MoreUtils qw(pairwise part);
my @list = ("word1", "word2", "word3", "word4");
my @confidences = (0.1, 0.9, 0.3, 0.6);

my $i = 0;
my @ret = part { $i++ % 2 } 
          grep { defined } 
          pairwise { $b > .4 ? ($a, $b) : undef } @list, @confidences;

print Dumper @ret;

Output:

$VAR1 = [
          'word2',
          'word4'
        ];
$VAR2 = [
          '0.9',
          '0.6'
        ];
like image 43
simbabque Avatar answered Dec 03 '25 09:12

simbabque