5

我希望首先根据长度对包含 (word, word.length) 的列表进行排序,然后按字母顺序对单词进行排序。所以给定:"I am a girl"输出应该是a:1, I:1, am:2, girl:4 我有以下代码,但不适用于所有示例

val lengths = words.map(x => x.length)
val wordPairs = words.zip(lengths).toList
val mapwords = wordPairs.sort (_._2 < _._2).sortBy(_._1)
4

2 回答 2

12

您可以按元组排序:

scala>  val words = "I am a girl".split(" ")
words: Array[java.lang.String] = Array(I, am, a, girl)

scala>  words.sortBy(w => w.length -> w)
res0: Array[java.lang.String] = Array(I, a, am, girl)

scala>  words.sortBy(w => w.length -> w.toLowerCase)
res1: Array[java.lang.String] = Array(a, I, am, girl)
于 2013-01-23T06:39:40.157 回答
-2

你可以在一行中做到这一点:

 "I am a girl".toLowerCase.split(" ").map(x => (x,x.length)).sortWith { (x: (String,Int), y: (String,Int)) => x._1 < y._1 }

或分两行:

 val wordPairs = "I am a girl".split(" ").map(x => (x,x.length))
 val result = wordPairs.toLowerCase.sortWith { (x: (String,Int), y: (String,Int)) => x._1 < y._1 }
于 2013-01-23T10:05:09.073 回答