perl中的二维数组排序
#!/usr/bin/perl
use Encode;
@ax=( [60,90,80,75,65], #语文科目成绩
[wang, LI,zhang,ki,huang] , #学生姓名
[75,95,65,85,80] , #英文成绩
[75,95,65,100,99], #数学成绩 ,假定所有的姓名和成绩都不相同
);
#sort{}ax; #我想按照数学成绩排顺序
for $i (0..$#ax){
for $x (0..$#{$ax[$i]}) {
print "$ax[$i][$x]\t";
}
print "\n"
};
#我想按照数学成绩排序,请高手指点# perl?排顺
[解决办法]
@ax=( [60,90,80,75,65],
[wang, LI,zhang,ki,huang],
[75,95,65,85,80],
[75,95,65,100,99],
);
sub sort_by_math {
$sid = @_;
$i = 0;
@bx = map {[$i++, $_]} @{@ax[$sid]};
@cx = sort {$a->[1] <=> $b->[1]} @bx;
@dx = map {$_->[0]} @cx;
for $x (@ax) {
print "$x->[$_]\t" for @dx;
print "\n";
}
};
sort_by_math(3);
@ax=( [60,90,80,75,65],
[wang, LI,zhang,ki,huang],
[75,95,65,85,80],
[75,95,65,100,99],
);
sub sort_by_math {
$sid = shift;
$i = 0;
@bx = map {[$i++, $_]} @{@ax[$sid]};
@cx = sort {$a->[1] <=> $b->[1]} @bx;
@dx = map {$_->[0]} @cx;
for $x (@ax) {
print "$x->[$_]\t" for @dx;
print "\n";
}
};
sort_by_math(3);
#!/usr/bin/perl
use Encode;
use List::MoreUtils 'zip';
@ax=( [60,90,80,75,65], #语文科目成绩
[wang, LI,zhang,ki,huang] , #学生姓名
[75,95,65,85,80] , #英文成绩
[75,95,65,100,99], #数学成绩 ,假定所有的姓名和成绩都不相同
);
@order = sort {$ax[3]->[$a]<=>$ax[3]->[$b]} 0..$#{$ax[0]}; # 按数学成绩排序的下标
print "@order\n";
for $i (0..$#ax){
for $x (0..$#{order}) {
print "$ax[$i][$order[$x]]\t";
}
print "\n"
};
In [25]: ax=[ [60,90,80,75,65],
...: ['wang', 'LI','zhang','ki','huang'],
...: [75,95,65,85,80],
...: [75,95,65,100,99],
...: ];
In [26]: byperson = zip(*ax)
In [27]: byperson.sort(key=lambda x: x[3])
In [28]: result = zip(*byperson)
In [29]: result
Out[29]:
[(80, 60, 90, 65, 75),
('zhang', 'wang', 'LI', 'huang', 'ki'),
(65, 75, 95, 80, 85),
(65, 75, 95, 99, 100)]