我想知道在给出List
:
val l = List("a","b","c","d","e","f","g","h","i","j","k","l","m" /*...,x,y,z*/)
对于每5个项目(或最后一个段的更少项目),应用如下函数:
...map(_.mkString(","))
这样我最终得到的List
看起来像是:
List("a,b,c,d,e","f,g,h,i,j","k,l,m,n,o",/*...,*/"u,v,w,x,y,"z")
这种类型的列表处理可能有一个共同的术语,但我并不知道它。基本上我是在对项目进行分组,所以使用zipWithIndex
然后在索引上修改5来指示分区的位置?
答案 0 :(得分:5)
您可以在列表中使用grouped(n)
方法。
val l = List("a","b","c","d","e","f","g","h","i","j","k","l","m")
l.grouped(5).map(_.mkString(",")).toList
结果
List("a,b,c,d,e", "f,g,h,i,j", "k,l,m"): List[String]