【问题标题】:How to use map with for loop inside in Scala?如何在Scala中使用带有for循环的map?
【发布时间】:2017-05-28 18:30:04
【问题描述】:

我需要在 for 循环中创建一个列表,但我无法做到。

我以前有这段代码可以正常工作:

val tasksSchedules = orders.map (order => {                
    // Creates list of TaskSchedules
    order.Product.Tasks.map(task => {                     
        // Create TaskSchedule
    })        
})

但是出现了一个新要求,我现在需要根据数量重复创建 TaskSchedule 列表。我现在有以下代码:

val tasksSchedules = orders.map (order => {
    // Repeats creation of TaskSchedules as many times as the value of Quantity
    // Creation of list is lost with this for.
    for (i <- 1 to order.Quantity) {
        // Creates list of TaskSchedules
        order.Product.Tasks.map(task => {                     
            // Create TaskSchedule
        })
    }    
})

没有 for 循环,一切都可以无缝运行。但是,使用 for 循环不会创建我认为可以预期的列表。本质上,我需要一个 for 循环构造,它可以让我迭代直到某个值,并且表现得像 map 函数,所以我也可以创建一个列表。

有这种事吗?这可行吗?

【问题讨论】:

    标签: scala loops


    【解决方案1】:

    当您执行 for 循环时,为了生成列表,您需要使用 yield 命令:

    val tasksSchedules = orders.map (order => {
      // Repeats creation of TaskSchedules as many times as the value of Quantity
      // Creation of list is lost with this for.
      for (i <- 1 to order.Quantity) yield {
          // Creates list of TaskSchedules
          order.Product.Tasks.map(task => {                     
              // Create TaskSchedule
          })
      }    
    

    })

    在这种情况下,它会给你一个列表列表。

    如果您只需要列表列表,请使用 flatmap 而不是 map。

    【讨论】:

    • 谢谢,它工作得很好,除了一件事。 yield 是返回一个 Vector 而不是 Seq。是否可以让它返回一个 Seq?
    • 你可以试试 for (i
    【解决方案2】:

    对于它的价值,理解被简单地重写为map() 调用。而不是您当前的实现(这是 IMO,不一致),您可以简单地使用 map()s 重写它:

    val tasksSchedules = orders.map { order =>
      // Repeats creation of TaskSchedules as many times as the value of Quantity
      // Creation of list is lost with this for.
      (1 to order.Quantity).toSeq.map { i =>
        // Creates list of TaskSchedules
        order.Product.Tasks.map { task =>
          // Create TaskSchedule
        }
      }
    }
    

    或者只是为了理解:

    val tasksSchedules = for (order <- orders) yield {
      // Repeats creation of TaskSchedules as many times as the value of Quantity
      // Creation of list is lost with this for.
      for (i <- (1 to order.Quantity).toSeq) yield {
        // Creates list of TaskSchedules
        for (task <- order.Product.Tasks) yield {
          // Create TaskSchedule
        }
      } 
    }
    

    【讨论】:

    • 是否可以采用您建议的第一种方法,同时仍然具有类似于正常 for 中的 i 的迭代变量?
    • 是的,只需将下划线 (_) 替换为 i。我只是使用了下划线,因为索引没有在任何地方被引用。我会更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多