【问题标题】:How to handle list of list in scala and add elements itertively如何在scala中处理列表并迭代添加元素
【发布时间】:2020-06-15 10:26:35
【问题描述】:

我是 scala 的新手,任何帮助将不胜感激

比如说,我在 for 循环中计算点 [Lat, long],如何将它们迭代地添加到可变列表中

例如:


var points = MutableList(List(Double,Double))

for( i <- 0 to 100 ){
var (lat,long) = customfunction() // lat and long returned are in double datatype
points+=List(lat,lon)

} 

面临的错误: command-3921379637506779:74:错误:类型不匹配; 发现:lat.type(基础类型为 Double) 要求:无 点+=列表(纬度,经度) ^ command-3921379637506779:74:错误:类型不匹配; 发现:lon.type(基础类型为 Double) 要求:无 点+=列表(纬度,经度)

我在使用可变列表或任何其他可用的最佳方法方面的方向是否正确,请告诉我

【问题讨论】:

    标签: java scala geometry scala-collections


    【解决方案1】:

    试试下面的代码:

    var points = new mutable.MutableList[List[Double]]
    
      for (i <- 0 to 5) {
        var (lat, long) = customfunction() // lat and long returned are in double datatype
        points += List(lat, long)
      }
    
     println(points)
    
      def customfunction(): (Double, Double) = {
        return (1.0, 1.0)
      }
    

    【讨论】:

      【解决方案2】:

      很难确定您实际上想要完成什么。 customfunction() 是返回一个元组 (Double,Double) 还是一个列表 List[Double]

      无论它返回什么,如果你想要一个包含 100 个此类元素的 List,那么试试这个。

      val points = List.fill(100)(customfunction())
      

      作为一般规则,避免突变。没有vars 和少数(如果有的话)可变集合。

      【讨论】:

        【解决方案3】:

        更好的方法是使用案例类,如下所示:

        case class LatLong(lat: Double, long: Double)
        
        var points: MutableList[LatLong] = MutableList()
        
        def customfunction(): LatLong = {
            LatLong(1.0, 1.0)
        }
        
        for (i <- 0 to 5) {
            var currLatLong = customfunction() // lat and long returned are in double datatype
            points += currLatLong
         }
        
        println(points)
        

        函数式方法

        case class LatLong(lat: Double, long: Double)
        
        def customfunction(): LatLong = {
            LatLong(1.0, 1.0)
        }
        
        // No mutable points list is required.
        val points = (0 to 5).map(e => customfunction()).toList
        
        println(points)
        
        // Output
        //List(LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0), LatLong(1.0,1.0))
        

        如果有帮助请告诉我!

        【讨论】:

          【解决方案4】:
          import scala.collection.mutable.ListBuffer
          
          val points = new ListBuffer[List[(Double, Double)]]()
          
          for( i <- 0 to 100 ) {
            var result: (Double, Double) = customfunction()
            points += List(result)
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-28
            • 1970-01-01
            • 2023-04-02
            • 2012-07-22
            • 2018-09-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多