改造的最佳方式是什么:
val arr: List[String]
致:
val mapArr: List[Tuple[Int, String]]
其中:
each Tuple is:
- String value is the an odd index element of the list
- Int the size of the previous value.
示例:
val stringArr = List("a", "aaa", "bb", "abc")
val resultShouldBe = List((1, "aaa"), (2, "abc"))
答案 0 :(得分:5)
您可以使用IterableLike.grouped
:
val result = stringArr
.grouped(2)
.collect { case List(toIndex, value) => (toIndex.length, value) }
.toList
哪个收益率:
scala> val stringArr = List("a", "aaa", "bb", "abc")
stringArr: List[String] = List(a, aaa, bb, abc)
scala> stringArr.grouped(2).collect { case List(toIndex, value) => (toIndex.length, value) }.toList
res1: List[(Int, String)] = List((1,aaa), (2,abc))