【问题标题】:appending elements to list of list in scala将元素附加到scala中的列表列表
【发布时间】:2020-09-02 07:01:59
【问题描述】:

我创建了一个空的 scala 可变列表

import scala.collection.mutable.ListBuffer
val list_of_list : List[List[String]] = List.empty

我想在下面添加元素

filtered_df.collect.map(
          r => {

            val val_list = List(r(0).toString,r(4).toString,r(5).toString)
            list_of_list += val_list
          }
        )

我得到的错误是

Error:(113, 26) value += is not a member of List[List[String]]
  Expression does not convert to assignment because receiver is not assignable.
            list_of_list += val_list

谁能帮忙

【问题讨论】:

  • 您必须将 val list_of_list 更改为 var list_of_list 并将 list_of_list 的类型更改为可变替代项

标签: scala scala-collections


【解决方案1】:

您的声明似乎有误:

val list_of_list : List[List[String]] = List.empty

表示您已声明 scala.collection.immutable.List,其操作返回一个新列表而不更改当前列表。

要修复错误,您需要将外部List 类型更改为您在声明上方导入的ListBuffer,如下所示:

val list_of_list : ListBuffer[List[String]] = ListBuffer.empty

此外,除非您想修改从DataFrame 收集的数据,否则您似乎不要在此处使用map,因此您可以将其更改为foreach

filtered_df.collect.foreach {
  r => {
    val val_list = List(r(0).toString,r(4).toString,r(5).toString)
    list_of_list += val_list
  }
}

此外,您可以通过使用不可变的ListfoldRight 以功能方式实现它,而无需诉诸ListBuffer,如下所示:

val list_of_list: List[List[String]] = 
  filtered_df.collect.toList
    .foldRight(List.empty[List[String]])((r, acc) => List(r(0).toString,r(4).toString,r(5).toString) :: acc)

toList用于在调用foldRightbecause it's not stack safe for Arrays时实现栈安全

More info about foldLeft and foldRight

【讨论】:

  • 不幸的是 foldRight 不是堆栈安全的,我更喜欢 foldLeft 而不是 foldRightfoldLeft 是堆栈安全的
  • @BorisAzanov 你是对的。它仅对不可变的List 是堆栈安全的。编辑了答案
【解决方案2】:

您必须将 val list_of_list 更改为 var list_of_list。仅此还不够,因为您还必须将 list_of_list 的类型更改为 mutable 替代方案。

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 2014-06-10
    • 1970-01-01
    • 2017-12-18
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2018-12-09
    相关资源
    最近更新 更多