简体   繁体   English

Scala基于字符串中的数字排序

[英]Scala Sort based on a number in the string

I have a file which has lines of the type: 我有一个具有以下行类型的文件:

A 2.3 B 5.6
A 5.4 B 3.5
A 5.6 B 3.4

I want to read the file and sort it based on the second column that is 2.3,5.4,5.6 and extend the sort to all the columns so the output should be: 我想读取文件并基于第二列(即2.3、5.4、5.6)对其进行排序,并将排序扩展到所有列,因此输出应为:

A 5.6 B 3.4
A 5.4 B 3.5
A 2.3 B 5.6

I was thinking of reading the file as list and then doing a match to get second column and then sorting. 我正在考虑将文件读取为列表,然后进行匹配以获取第二列,然后进行排序。 Is there a better way? 有没有更好的办法?

You have the right idea, but be aware that there is a command line utility to do this for you: 您有正确的想法,但请注意,有一个命令行实用程序可以为您执行此操作:

$ sort -k2 -n -r
A 2.3 B 5.6
A 5.4 B 3.5
A 5.6 B 3.4
^D
A 5.6 B 3.4
A 5.4 B 3.5
A 2.3 B 5.6

If you really wanted to do it in scala, you would need to read it into memory, and then sortWith a comparator that looks at the second field in each row. 如果您真的想在scala中执行此操作,则需要将其读取到内存中,然后使用比较器对sort进行排序,该比较器将查看每行的第二个字段。

You probably want something like 您可能想要类似

val src = scala.io.Source.fromFile("filename")
val lines = src.getLines.toSeq.sortBy(line => -line.split(' ').apply(1).toDouble)
src.close

(the negative is to sort largest-first; default is smallest-first). (否定的是将“最大的优先”排序;默认为“最小的优先”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM