How to perform transpose on List of Lists in scala?

后端 未结 2 1421
忘了有多久
忘了有多久 2020-12-18 22:59

I have a scala list of following structure:

val list = List(
  List(a1,a2,a3,a4,a5),
  List(b1,b2,b3,b4,b5),
  List(c1,c2,c3,c4,c5)
)
         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 00:02

    Here is a manual implementation of the library function.

    object CustomZipTest extends App{
      val list1: List[String] = List("a", "1", "w")
    
      val list2: List[String] = List("b", "2", "x")
    
      val list3: List[String] = List("c", "3", "y")
    
      val list4: List[String] = List("d", "4", "z")
    
      def customZip[T](list: List[T] *): List[List[T]] = {
        def stripOneLevel(list: Seq[List[T]]): (Seq[List[T]], List[T]) = {
          list.foldRight(Seq(): Seq[List[T]], List(): List[T]){ (e, acc) =>
            if (e.size == 1) (acc._1, e.head +: acc._2)
            else (e.tail +: acc._1, e.head +: acc._2)
          }
        }
    
        def strip(list: Seq[List[T]], acc: List[List[T]]): List[List[T]] = {
          list match {
            case Nil => acc
            case x+:xs =>
              val stripped = stripOneLevel(list)
              strip(stripped._1, stripped._2 +: acc)
          }
        }
    
        strip(list, List()).reverse
      }
    
      println(customZip(list1, list2, list3, list4))
    
    }
    

提交回复
热议问题