如何使用Scala将字符串中的值组合起来?

3

我希望将字符串中的数值合并。例如:

Let A = a,b,c,d

我希望将它们组合成以下形式:

AComb = a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,bcd,acd

你是说让 A = a,b,c,d?应该是 val A = Set("a", "b", "c", "d") 吧? - Govind Singh
1个回答

5
假设A是一个Set
scala> val A =Set("a","b","c","d")
A: scala.collection.immutable.Set[String] = Set(a, b, c, d)


scala> val AComb=A.toSet[String].subsets.map(_.mkString).toVector
AComb: Vector[String] = Vector("", a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd)

我认为您不需要第一个元素,您可以尝试:
scala> val AComb=A.toSet[String].subsets.map(_.mkString).toVector.tail
AComb: scala.collection.immutable.Vector[String] = Vector(a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd)

删除第一个和最后一个元素

scala> val AComb=A.toSet[String].subsets.map(_.mkString).toVector.init.tail
AComb: scala.collection.immutable.Vector[String] = Vector(a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd)

抱歉,我只能回答英文问题。
scala> val xc1=Set("sunny","hot","high","FALSE","no")
xc1: scala.collection.immutable.Set[String] = Set(sunny, FALSE, hot, no, high)

scala> val AComb=xc1.toSet[String].subsets.map(_.mkString(" ")).toVector.tail;
AComb: scala.collection.immutable.Vector[String] = Vector(sunny, FALSE, hot, no, high, sunny FALSE, sunny hot, sunny no, sunny high, FALSE hot, FALSE no, FALSE high, hot no, hot high, no high, sunny FALSE hot, sunny FALSE no, sunny FALSE high, sunny hot no, sunny hot high, sunny no high, FALSE hot no, FALSE hot high, FALSE no high, hot no high, sunny FALSE hot no, sunny FALSE hot high, sunny FALSE no high, sunny hot no high, FALSE hot no high)

如何删除最后一个元素?我只需要 n-1 的组合。 - rosy
错误:(144,28)类型参数[String]不符合方法toSet的类型参数边界[B>: Any] val AComb = xc1.toSet[String].subsets.map(_.mkString).toVector.init.tail ^ - rosy
先生,我的集合xc1是Set(sunny,hot,high,FALSE,no),如果我应用这个val AComb = xc1.toSet [String] .subsets.map(_ .mkString).toVector.tail,结果是Vector(sunny,hot,high,FALSE,no)......,它没有给出任何组合。 - rosy
先生,如果我像这样给出Set("a","b","c","d"),它会给出正确的答案。但是我的初始行是row1 = sunny,hot,high,FALSE,no,所以我将其转换为集合,即A = mutable.Set(row1),因此xc1 = Set(sunny,hot,high,FALSE,no)。然后我将您的代码应用于xc1,但它不起作用... - rosy
val config = new SparkConf().setAppName("Apriori_Algo").setMaster("local") val sc = new SparkContext(config) val data = sc.textFile("/home/data/weather.csv").cache() val eachline = data.flatMap(line => line.split("/n")) var rowelemset: scala.collection.Set[String] = null val rowlist = eachline.map(x2 => { rowelemset = mutable.Set(x2) rowelemset }).collect() rowlist.foreach(i => println(i)) val st = rowlist.map(xc1 => { val AComb = xc1.toSet[String].subsets.map(_.mkString).toVector.tail AComb }) st.foreach(println) - rosy
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接