Scala:从Vector中删除元素

时间:2016-10-06 17:57:29

标签: scala

我有一个Vector,想要从Vector中删除元素。我怎么能在Scala中做到?我的输入是Vector [2.0,3.0,0.3,1.0,4.0] - > Vector [Double]我想要一个Vector [2.0,0.3,4.0]作为输出,所以我想要从我的输入Vector ...

中删除索引1和3的元素
def removeElementFromVector(input: Vector) = {   
  val inputAsArray = input.toArray

  inputAsArray

  // ...
  val reducedInputAsVector = inputAsArray.toVector 
}

5 个答案:

答案 0 :(得分:0)

您可以使用filter方法删除它们。

> val reducedInputVector = input.filter(x => !(Array(1,3) contains input.indexOf(x)))
reducedInputVector: scala.collection.immutable.Vector[Double] = Vector(2.0, 0.3, 4.0)

答案 1 :(得分:0)

我的输入是:矢量[2.0,3.0,0.3,1.0,4.0] - >矢量[双]我想要一个Vector [2.0,3.0,0.3,4.0]作为输出,所以我想删除我的输入Vector中带有索引1和3的元素。 Sry我的问题还不够明确。

答案 2 :(得分:0)

是的,您可以使用过滤器来实现它,但我们需要添加索引来删除索引处的元素:

Ex:你的矢量(scala.collection.immutable.Vector [Double]):

scala> val v1 = val v1 = Vector(2.2, 3.3, 4.4, 5.5, 6.6, 4.4)

Output: Vector(2.2, 3.3, 4.4, 5.5, 6.6, 4.4)

现在,我们将删除索引2处的元素:

scala> var indexRemove=2

scala> val v2 = v1.zipWithIndex.filter(x => x._2!=indexRemove).map(x=>x._1).toVector
Output: Vector(2.2, 3.3, 5.5, 6.6, 4.4)

现在,我们将删除索引3处的元素

scala> var indexRemove=3
scala> val v2 = v1.zipWithIndex.filter(x => x._2!=indexRemove).map(x=>x._1).toVector
Output: Vector(2.2, 3.3, 4.4, 6.6, 4.4)

希望这有帮助。

答案 3 :(得分:0)

我用申请解决了这个问题:

val vec1 = Vector(2.0,3.0,0.3,1.0, 4.0)
val vec2 = Vectors.dense(vec1.apply(0), vec1.apply(1),vec1.apply(2), vec1.apply(4))

输出

vec1: scala.collection.immutable.Vector[Double] = Vector(2.0, 3.0, 0.3, 1.0, 4.0)
vec2: org.apache.spark.mllib.linalg.Vector = [2.0,3.0,0.3,4.0]

答案 4 :(得分:0)

def deleteItem[A](row: Vector[A], item: Int): Vector[A] = {
  val (a,b) = row.splitAt(item)
  if (b!=Nil) a ++ b.tail else a
}
相关问题