1
How to sort a list with a given order?Perl - 如何按给定顺序对数组值进行排序?
我们已经讨论了如何使用map和$ _根据给定顺序对列表进行排序。今天我有另一个问题。
我有同样的排序依据:
my @orderby = ('car', 'boat', 'chicken', 'cat', 'dog', 'mouse');
# or if it's better to the code:
my %orderby = ('car' => 0,
'boat' => 1,
'chicken' => 2,
'cat' => 3,
'dog' => 4,
'mouse' => 5);
现在我已经被排序依据被下令需要满足以下条件:
print Dumper \%toys;
$VAR = {
'animals' => [
[
'feather', 'cluck-2', 'chicken', 'white'
],
[
'bald', 'bark', 'dog', 'black stripes'
],
[
'feather', 'cluck-2', 'chicken', 'white'
]
],
'notanima' => [
[
'paited', 'motor', 'boat', 'red'
],
[
'painted', 'motor', 'car', 'blue on top'
]
]
};
的代码需要使用3列基于排序依据排序。你需要为动物和notanima使用相同的装饰。 的重新排列后,$ VAR将是:
$VAR = {
'animals' => [
[
'feather', 'cluck-2', 'chicken', 'white'
],
[
'feather', 'cluck-2', 'chicken', 'white'
],
[
'bald', 'bark', 'dog', 'black stripes'
]
],
'notanima' => [
[
'painted', 'motor', 'car', 'blue on top'
],
[
'paited', 'motor', 'boat', 'red'
]
]
};
order %toys{key} by orderby;
我曾试图改变这种@ikegami提供
my %counts; ++$counts{$_} for @list;
my @sorted = map { ($_) x ($counts{$_}||0) } @orderby;
地图解决方案,但我没有成功。 你们有什么想法,我怎么能实现这个目标?
Thx提前!
更新!
我试图用从池上的建议,我已经做到了这一点:
# that first foreach will give one ARRAY for animals and one ARRAY for notanima
foreach my $key (keys %toys)
{
# that one will give me access to the ARRAY referenced by the $key.
foreach my $toy_ref ($toys{$key})
{
my %orderby = map {$orderby[$_] => $_} 0..$#orderby;
my @sorted = sort { $orderby{$a} <=> $orderby{$b} } @{$toy_ref};
# my @sorted = sort { $orderby{$a} <=> $orderby{$b} } $toy_ref;
print Dumper @sorted;
}
}
首先,这给了我警告:
Use of uninitialized value in numeric comparison (<=>) at....
我的排序为notanima(的结果会忽视动物,所以后也不会那么大):
基于排序依据$VAR1 = [
'paited', 'motor', 'boat', 'red'
];
$VAR2 = [
'painted', 'motor', 'car', 'blue on top'
];
,打印顺序必须是:
$VAR1 = [
'painted', 'motor', 'car', 'blue on top'
];
$VAR2 = [
'paited', 'motor', 'boat', 'red'
];
汽车需要先来。 我做错了什么?
[Perl:如何按给定顺序对列表进行排序?](http:// stackoverflow。com/questions/14730683/perl-how-to-sort-a-list-with-a-given-order) –
如果上一个答案不起作用,请不要再提问相同的问题;更新您的旧问题并取消标记答案。 –
为什么你使用标签为“人头屎”的解决方案? – ikegami