Perl: Sorting 2D array with multiple columns based on a particular column

﹥>﹥吖頭↗ 提交于 2019-12-06 04:36:34

问题


Pseudo code:

my @unsortedArray = { ["Harry", 10], ["Tim", 8], ["Joe", 3]};
my @sortedArray = ?????

Final sortedArray should be sorted based on col-2 (integers), taking care of the 1-to-1 relationship with the "Name of the person" (col-1). Final result should look like:

sortedArray should be { ["Joe", 3], ["Tim", 8], ["Harry", 10] }; 

回答1:


You can give a predicate to sort, that is: a function which is evaluated to compare elements of the list.

my @unsorted = ( ["Harry", 10], ["Tim", 8], ["Joe", 3] );

my @sorted = sort { $a->[1] <=> $b->[1] } @unsorted;

In the predicate (the expression in curly braces), $a and $b are the elements of the outer list which are compared.

sort is only concerned with one-dimensional lists, so it won't mess with the internal structure of the elements of the outer list. So the relationship between name and number is retained effortlessly.

Refer to perldoc -f sort and perldoc perlop for more details.




回答2:


A more efficient solution, especially for larger arrays, may be to use List::UtilsBy::nsort_by:

use List::UtilsBy qw( nsort_by );

my @unsorted = ( ["Harry", 10], ["Tim", 8], ["Joe", 3] );

my @sorted = nsort_by { $_->[1] } @unsorted;

While in small cases the overhead is not likely to be noticed, for more complex functions the O(n log n) key extraction cost becomes higher, and it is more preferrable to extract the "sort key" of each value only once, which is what nsort_by does.



来源:https://stackoverflow.com/questions/10318186/perl-sorting-2d-array-with-multiple-columns-based-on-a-particular-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!