的Perl:数值排序在哈希2阵列(Schwarzian变换) [英] Perl: Numerical sort of arrays in a hash 2 (Schwarzian Transform)
问题描述
这实际上是该线程的后续:
的Perl:在哈希 数字排序阵列p>
由于我目前的code是一个有点不同我不能修改原来的问题,所以我只是问这是另外一个问题。
好吧使用Schwarzian变换后,我有这样的:
我@mylines =(0.899 0.92猫,
9.999 0.001狗,
-0.52 0.3矮胖,
13.52 0.09布博
-1.52 0.98保姆,
3.52 0.34拉拉);我@sorted = {地图加入'',@ $ _}
反向排序{$ A-> [0] CMP $ B-> [0]或$ A-> [1] => $ B-> [1]}
图{[拆分]}(@mylines);打印$ _ \\ n表示@sorted;
我期望的输出被第一列,则第二个第一排序,但事实证明,这样的:
9.999 0.001狗
3.52 0.34拉拉
13.52 0.09布博
0.899 0.92猫
-1.52 0.98保姆
-0.52 0.3矮胖
我想这是因为它做一个字符排序...但我需要它数字顺序排序。我需要把一个类似Java的parseInt函数()中的某处排序功能?
您在第一列上做一个 CMP
。这意味着它进行排序为文本。您的排序功能应该是:
排序{$ A-> [0]< = GT; $ B-> [0]或$ A-> [1] => $ B-> [1]} ...
这使得输出:
13.52 0.09布博
9.999 0.001狗
3.52 0.34拉拉
0.899 0.92猫
-0.52 0.3矮胖
-1.52 0.98保姆
但是,你不应该需要把逆转
排序之前,因为你总是可以逆转的条件:
排序{$ B-> [0]< = GT; $ A-> [0]或$ B-> [1] => $ A-> [1]} ...
This is actually a follow-up of this thread: Perl: Numerical sort of arrays in a hash
I couldn't edit the original question because my current code is a bit different, so I'm just asking this as another question.
Okay after using the Schwarzian Transform, I have this:
my @mylines =("0.899 0.92 cat",
"9.999 0.001 dog",
"-0.52 0.3 humpty",
"13.52 0.09 bumbo",
"-1.52 0.98 nanny",
"3.52 0.34 lala");
my @sorted = map { join ' ', @$_ }
reverse sort { $a->[0] cmp $b->[0] or $a->[1] <=> $b->[1] }
map { [ split ] } (@mylines);
print "$_\n" for @sorted;
I would expect the output to be sorted first by the first column, then the second, but it turns out like this:
9.999 0.001 dog
3.52 0.34 lala
13.52 0.09 bumbo
0.899 0.92 cat
-1.52 0.98 nanny
-0.52 0.3 humpty
I suppose that's because it's doing a character sort... but I need it numerically sorted. Do I need to put a java-like "parseInt()" somewhere in the sort function?
You are doing a cmp
on the first column. That means it sorts it as text. Your sort function should be:
sort { $a->[0] <=> $b->[0] or $a->[1] <=> $b->[1] } ...
Which makes the output:
13.52 0.09 bumbo
9.999 0.001 dog
3.52 0.34 lala
0.899 0.92 cat
-0.52 0.3 humpty
-1.52 0.98 nanny
However, you should never need to put a reverse
before sort, because you can always reverse the terms:
sort { $b->[0] <=> $a->[0] or $b->[1] <=> $a->[1] } ...
这篇关于的Perl:数值排序在哈希2阵列(Schwarzian变换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!