【问题标题】:scala - if/else in a for loopscala - for 循环中的 if/else
【发布时间】:2018-07-03 15:14:25
【问题描述】:

如果我像这样使用两个 for 循环,我会得到一个 List[List[Int]],但我怎样才能得到一个 List[Int]? 我不知道如何只在一个 for 循环中编写 if/else 语句,有人可以帮我吗?

def example:  (List[(Int, Int)], Int,Int) => List[Int] ={
    (list, p, counter) => 
    if (counter >=0)
        for(x<-list(i._1); if ( x._1 ==p))yield x._2
        for(x<-list(i._1); if ( x._1 !=p))yield example((x._1,x._2+i._2):: Nil,p,counter-1)
    else { ....}
}

【问题讨论】:

  • 语法不正确,你有没有尝试运行你写的函数?
  • 因为return,它不起作用,这就是为什么我想改变它但我不知道如何
  • @user10027527 你可以为我们发布整个代码,就像 else 语句中的内容一样,你也可以为上面的代码发布一个示例输入。

标签: scala loops for-loop if-statement


【解决方案1】:

首先,正如所写,您发布的代码甚至不是有效的定义。如果您有一些工作但返回的类型与所需的不同,请发布该工作代码。

话虽如此,如果你有List[List[Int]] 并且想要List[Int],那么方法就是flatten

用法:

scala> val nestedList = List(List(1, 2), List(3, 4), List(5, 6))
nestedList: List[List[Int]] = List(List(1, 2), List(3, 4), List(5, 6))

scala> val flattenedList = nestedList.flatten
flattenedList: List[Int] = List(1, 2, 3, 4, 5, 6)

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2019-12-04
    • 2021-09-16
    • 1970-01-01
    • 2022-01-10
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多