【发布时间】:2014-01-14 08:05:47
【问题描述】:
我是一个新手,在使用 PHP 多年后尝试学习 Scala。我要解决的问题非常简单,但不确定如何在 Scala 中解决。基本上,我正在从具有人名、姓氏和成绩的文件中读取内容。我需要阅读文件并按等级对名称进行排序。
文件是这样的。
Aoe Samore 3.1
Boe Sbmore 2.2
Coe Scmore 3.9
Doe Sdmore 2.4
Eoe Semore 3.5
Foe Sfmore 2.6
Goe Sgmore 3.7
Hoe Shmore 2.9
Ioe Simore 3.1
Joe Sjmore 1.2
Koe Skmore 3.2
Loe Slmore 4.0
最终结果应该是这样显示的
Loe Slmore 4
Coe Scmore 3.9
Goe Sgmore 3.7
Eoe Semore 3.5
Koe Skmore 3.2
Aoe Samore 3.1
Ioe Simore 3.1
Hoe Shmore 2.9
Foe Sfmore 2.6
Doe Sdmore 2.4
Boe Sbmore 2.2
Joe Sjmore 1.2
这就是我在 PHP 中的做法
$content = file_get_contents('grd.txt');
$lines = explode("\n",$content);
$grades_with_information = [];
foreach($lines as $line) {
$temp = explode(' ',$line);
$temp[2] = (float)$temp[2];
$grades_with_information[] = $temp;
}
usort($grades_with_information, function($a, $b) {
if ($a[2] == $b[2]) {
return 0;
}
return ($a[2] > $b[2]) ? -1 : 1;
});
foreach($grades_with_information as $grade_with_information){
echo $grade_with_information[0].' '
.$grade_with_information[1].' '
.$grade_with_information[2]
.'<br>';
}
到目前为止,我们如何在 Scala 中做到这一点,我已经做到了
val source = scala.io.Source.fromFile("grd.txt")
val lines = source.getLines()
for (a <- lines) {
}
source.close()
有什么建议/帮助/线索吗?
【问题讨论】:
-
将标题从“如何在 Scala 中对多维进行排序”更改为“如何根据其中的值对行进行排序”。