简体   繁体   English

在Scala中,如何以反向尺寸将列表中的元素分组?

[英]In Scala how to group elements in list with reverse dimension?

Given: 鉴于:

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))

How to reverse dimension and group elements in a in this way: 如何扭转在维和族元素a以这种方式:

List(List(1, 4, 7), List(2, 5, 8), List(3, 6))

You can try this method, find out the length of the longest List and then collect elements from each sub list while looping through the indices: 您可以尝试此方法,找出最长列表的长度,然后在循环遍历索引时从每个子列表中收集元素:

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))

Maybe you want transpose method, but official transpoes method doesn't support unequal length of sublist. 也许你想调换的方法,但官方transpoes方法不支持长度不等的子列表。 maybe you want to try: 也许您想尝试:

Is there a safe way in Scala to transpose a List of unequal-length Lists? Scala中有安全的方法来转译不等长列表吗?

Should use the groupBy method to group elements in the list. 应该使用groupBy方法对列表中的元素进行分组。 In your example, you are grouping every third element. 在您的示例中,您将对每三个元素进行分组。 In my solution, I am using the modulus operator to group every third element in the list: 在我的解决方案中,我正在使用模运算符将列表中的每三个元素分组:

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))

If you want the results sorted (as in your example) then add the sortBy() at the end: 如果要对结果进行排序(如您的示例中所示),请在最后添加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.

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