【问题标题】:How to create seperate lists from a list using scala?如何使用scala从列表中创建单独的列表?
【发布时间】:2015-01-05 00:21:57
【问题描述】:

我有以下列表 -

List((name1,A1,176980), (name2,A2,0), (name3,A3,1948), (name4,A4,95676))

从上面的列表中,我想分别创建单独的列表元素列表,例如 element1、element2 和 element3。

我想要单独的列表,例如-

List(name1,name2,name3,name4)

List(A1,A2,A3,A4) 

List(176980,0,1948,95676)

如何使用 scala 获得以上列表???

【问题讨论】:

    标签: list scala collections scala-collections


    【解决方案1】:

    如果您总是有 3 元组,则有一个标准方法:

    scala> list.unzip3
    res1: (List[String], List[String], List[Int]) = 
     (List(name1, name2, name3, name4),List(A1, A20, A3, A4),List(176980, 0, 1948, 95676))
    

    还有 unzip 用于 2 元组。

    【讨论】:

      【解决方案2】:

      天真的解决方案:

      val list = List(
        ("name1","A1",176980),
        ("name2","A20",0),
        ("name3","A3",1948),
        ("name4","A4",95676))
      
      list.map(_._1)    
      list.map(_._2)    
      list.map(_._3)    
      

      一些概括的版本:

      def key(products: List[Product], num: Int) = {
        products.map(_.productElement(num))
      }
      
      key(list, 0) // res3: List[Any] = List(name1, name2, name3, name4)
      key(list, 1) // res4: List[Any] = List(A1, A20, A3, A4)
      key(list, 2) // res5: List[Any] = List(176980, 0, 1948, 95676)
      

      甚至对于任何数量的产品:

      def key(products: List[Product], num: Int) = {
        products.map { p =>
          Option(p)
            .filter(_.productArity > num)
            .map(_.productElement(num))
            .getOrElse(None)
        }
      }
      

      【讨论】:

        【解决方案3】:
        scala> List(("name1","A1",176980), ("name2","A2",0), ("name3","A3",1948))
        res9: List[(String, String, Int)] = List((name1,A1,176980), (name2,A2,0), (name3,A3,1948))
        
        scala> res9.map(_._1)
        res10: List[String] = List(name1, name2, name3)
        
        scala> res9.map(_._2)
        res11: List[String] = List(A1, A2, A3)
        
        scala> res9.map(_._3)
        res12: List[Int] = List(176980, 0, 1948)
        

        【讨论】:

          猜你喜欢
          • 2015-01-17
          • 2017-10-09
          • 2018-11-19
          • 2020-08-04
          • 2018-08-22
          • 2016-10-30
          • 2021-12-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多