一种删除二维阵列中某些列的功能性方法



假设我有一个形式为Seq[Array[String]]的2D数组,其中第一个索引显示行。第一行始终是标题行。目标是过滤掉那些标题为空的列。例如,如果表的内容是(3乘3,第一行作为标题):

 ,  t,
a,  c,  e 
b,  d,  f 

val table = Seq(Array("", "t", ""), Array("a", "c", "e"), Array("b", "d", "f"))

这里是所需的输出,删除空标题后:

t
c
d

filter生成一个数组很容易,但这里的困难在于,需要根据标题行过滤所有数组。知道怎么做吗?

尝试:

val indices = table.head.zipWithIndex
                   .filter { case (t, i) => t != "" }
                   .map { case (t, i) => i }
table.map(indices collect _)
// > res: Seq[Array[String]] = List(Array(t), Array(c), Array(d))

实现这一点的一种方法是使用transpose运算符:

table.transpose.filterNot(_.head.isEmpty)
> Seq[Seq[String]] = List(List(t, c, d))

相关内容

最新更新