I'm trying to do the following. I have a predefined list to be used as a "order by" on an given list.
my @orderby = ( 'car', 'boat', 'chicken', 'cat', 'dog', 'mouse');
or
my %orderby = ( 'car' => 0, 'boat' => 1, 'chicken' => 2, 'cat' => 3, 'dog' => 4, 'mouse' => 5);
my @list = ('boat', 'car', 'mouse', 'chicken');
I tried infinite ways to sort it and I didn't get what I want. I have searched on google, and here, but I did not found the answer.
@list
need to be sorted in that way:
sort @list using %orderby
The print that I want after the sort:
car, boat, chicken, mouse
BTW, @list can have duplicated entries:
my @list = ('boat', 'car', 'mouse', 'chicken', 'mouse', 'car');
In that case, the print need to be:
car, car, boat, chicken, mouse, mouse
Do you guys have a solution for that? or maybe another approach. Thanks!!
sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.
If you want to sort the original list because you, say, hold references to it elsewhere, you can assign to it the sorted list: my_list[:] = [my_list[i] for i in sorted_indexes] # [:] is key!
Use list. sort() to sort a list in reverse order. Call list. sort(reverse=False) with reverse set equal to True to sort list in reverse order.
my @orderby = qw( car boat chicken cat dog mouse );
my @list = qw( boat car mouse chicken );
my %orderby = map { $orderby[$_] => $_ } 0..$#orderby;
my @sorted = sort { $orderby{$a} <=> $orderby{$b} } @list;
Or if you want to mess with people's minds,
my @orderby = qw( car boat chicken cat dog mouse );
my @list = qw( boat car mouse chicken );
my %counts; ++$counts{$_} for @list;
my @sorted = map { ($_) x ($counts{$_}||0) } @orderby;
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