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);
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 ];
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'
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With