Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list with a given order?

Tags:

list

sorting

perl

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!!

like image 919
JGG Avatar asked Feb 06 '13 13:02

JGG


People also ask

How do you sort a list in a specific order in Python?

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.

How do you sort a list by index?

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!

How do you sort a list in reverse order in Python?

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.


1 Answers

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;
like image 183
ikegami Avatar answered Sep 28 '22 13:09

ikegami