假设我有一个形式为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))