在List的切片上映射

时间:2016-05-24 20:47:32

标签: scala

我想知道在给出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来指示分区的位置?

1 个答案:

答案 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]