![](/img/trans.png)
[英]How to group by elements of tuple in Scala and map to list of new elements?
[英]In Scala how to group elements in list with reverse dimension?
鑒於:
scala> val a = (1 to 8).toList.grouped(3).toList
a: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8))
如何扭轉在維和族元素a
以這種方式:
List(List(1, 4, 7), List(2, 5, 8), List(3, 6))
您可以嘗試此方法,找出最長列表的長度,然后在循環遍歷索引時從每個子列表中收集元素:
val maxLength = a.map(_.length).max
// maxLength: Int = 3
(0 until maxLength) map (i => a flatMap (List(i) collect _))
// res45: scala.collection.immutable.IndexedSeq[List[Int]] =
// Vector(List(1, 4, 7), List(2, 5, 8), List(3, 6))
也許你想調換的方法,但官方transpoes方法不支持長度不等的子列表。 也許您想嘗試:
應該使用groupBy方法對列表中的元素進行分組。 在您的示例中,您將對每三個元素進行分組。 在我的解決方案中,我正在使用模運算符將列表中的每三個元素分組:
val a = (1 to 8).toList.groupBy(_ % 3).values.toList
a: List[List[Int]] = List(List(2, 5, 8), List(1, 4, 7), List(3, 6))
如果要對結果進行排序(如您的示例中所示),請在最后添加sortBy():
val a = (1 to 8).toList.groupBy(_ % 3).values.toList.sortBy(_(0))
a: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.