定义一个2d列表并在for循环中添加列表,scala

时间:2016-11-30 14:55:38

标签: scala list append 2d

我想在for循环之前定义一个2d列表,之后我想在for循环中附加1d列表,如下所示:

var 2dEmptyList: listOf<List<String>> 
for (element<-elements){
    ///do some stuff
    2dEmptyList.plusAssign(1dlist) 
}

上面的代码不起作用。但我似乎无法找到解决方案而且它很简单!

2 个答案:

答案 0 :(得分:1)

scala> val elements = List("a", "b", "c")
elements: List[String] = List(a, b, c)

scala> val twoDimenstionalList: List[List[String]] = List.empty[List[String]]
twoDimenstionalList: List[List[String]] = List()

scala> val res = for(element <- elements) yield twoDimenstionalList ::: List(element)
res: List[List[java.io.Serializable]] = List(List(a), List(b), List(c))

更好的是:

scala> twoDimenstionalList ::: elements.map(List(_))
res8: List[List[String]] = List(List(a), List(b), List(c))

答案 1 :(得分:1)

如果您希望2dEmptyList可变,请考虑使用scala.collection.mutable.ListBuffer

scala> val ll = scala.collection.mutable.ListBuffer.empty[List[String]]
ll: scala.collection.mutable.ListBuffer[List[String]] = ListBuffer()

scala> ll += List("Hello")
res7: ll.type = ListBuffer(List(Hello))

scala> ll += List("How", "are", "you?")
res8: ll.type = ListBuffer(List(Hello), List(How, are, you?))