如何按给定顺序对列表进行排序? [英] How to sort a list with a given order?
问题描述
我正在尝试执行以下操作.我有一个预定义的列表,可以用作给定列表上的排序依据".
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');
我尝试了无数种方式对它进行排序,但我没有得到想要的东西.我已经在Google和此处进行了搜索,但是没有找到答案.
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
需要以这种方式排序:
@list
need to be sorted in that way:
sort @list using %orderby
排序后我想要的打印件:
The print that I want after the sort:
car, boat, chicken, mouse
顺便说一句,@ list可以有重复的条目:
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!!
推荐答案
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;
这篇关于如何按给定顺序对列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!