[英]combination of array elements in scala
我有一個數組 [Int] 的 rdd,如下所示:
([0,1,7],[0,1],[0,1,3],...)
現在我想獲取每個內部列表中的數組組合,如下所示:
Array [[0,1,7], [0,7],[1,7],[7],[0,1],[1],[0,1,3],[0,3],[1,3],[3]]
最好的方法是什么?
您可以使用來自數據集 API 的Seq
trait 和flatMap
的combinations
來做到這一點:
import spark.implicits._
val df = Seq(
Array(0, 1, 7),
Array(0, 1),
Array(0, 1, 3)
).toDF("arr")
df.show()
val res = df.flatMap{
row =>
val rowSeq: Seq[Int] = row.getAs[Seq[Int]](0)
(1 to rowSeq.length).flatMap(n => rowSeq.combinations(n))
}.collect().foldLeft(Set.empty[Array[Int]]){
case (arrAcc, seqInt) => arrAcc + seqInt.toArray
}
println(res.map(a => a.mkString("[", ", ", "]")).mkString("[", ", ", "]"))
output 將是:
df.show()
+---------+
| arr|
+---------+
|[0, 1, 7]|
| [0, 1]|
|[0, 1, 3]|
+---------+
res
[[1], [1, 7], [0], [0, 7], [0, 1], [3], [0, 1, 3], [0, 3], [7], [0, 1, 7], [1, 3]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.