我希望首先根据长度对单词(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)
答案 0 :(得分: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)
答案 1 :(得分:-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 }