比较两个列表并获取相同元素的索引

问题描述:

val a = List(1,1,1,0,0,2) 
val b = List(1,0,3,2) 

我想要获得“列表a”中存在的“列表b”元素的索引列表。 输出。这里是清单(0,1,3)比较两个列表并获取相同元素的索引

我想这

for(x <- a.filter(b.contains(_))) yield a.indexOf(x)) 

对不起。我错过了这一点。列表大小可能会有所不同。编辑清单

有没有更好的方法来做到这一点?

如果您想要索引的结果,通常以索引开始是有用的。

b.indices.filter(a contains b(_)) 

REPL测试。

scala> val a = List(1,1,1,0,0,2) 
a: List[Int] = List(1, 1, 1, 0, 0, 2) 

scala> val b = List(1,0,3,2) 
b: List[Int] = List(1, 0, 3, 2) 

scala> b.indices.filter(a contains b(_)) 
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 3) 
+0

感谢您的回复。但我现在纠正了这个问题。 – sowmiyaksr

+0

这个答案更优雅IMO。 –

+0

我得到,ArrayIndexOutOfBoundException使用此没有任何修改。 – sowmiyaksr

val result = (a zip b).zipWithIndex.flatMap { 
    case ((aItem, bItem), index) => if(aItem == bItem) Option(index) else None 
} 

a zip b将返回从具有在B​​ A匹配对所有元素。 例如,如果a较长(如在您的示例中),则结果将为List((1,1),(1,0),(1,3),(0,2))(该列表将为b.length long)。
然后你也需要索引,那就是zipWithIndex
由于您只需要索引,因此会返回Option[Int]并将其平坦化。

+0

我可能会使用收集,以避免选项,但我的答案会类似于这个 – pedrorijo91

您可以使用索引for此:

for{ i <- 0 to b.length-1 
    if (a contains b(i)) 
    } yield i 

scala> for(x <- b.indices.filter(a contains b(_))) yield x; 
res27: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 1, 3) 

这里是另一种选择:

scala> val a = List(1,1,1,0,0,2) 
a: List[Int] = List(1, 1, 1, 0, 0, 2) 

scala> val b = List(1,0,3,2) 
b: List[Int] = List(1, 0, 3, 2) 

scala> b.zipWithIndex.filter(x => a.contains(x._1)).map(x => x._2) 
res7: List[Int] = List(0, 1, 3) 

我也想指出的是您原来的想法:在b寻找元素那么在a,然后获取这些元素的索引将无法正常工作,除非在a中包含b中的所有元素是唯一的,indexOf返回第一个元素的索引。只是站起来。