我有2个列表
val listA = List("Mary", "Harry", "Marry", "Harry", "Marry")
val listB = List("Mary", "Harry", "Marry", "Harry", "Marry")
现在我想知道列表中所有Harry
出现的索引是否相同。在scala中执行此操作的最佳方法是什么?
答案 0 :(得分:4)
我使用迭代器只根据需要进行比较,如下所示:
def indexesOf(ls: List[String], word: String) =
ls.iterator.zipWithIndex.collect { case (`word`, i) => i }
indexesOf(listA, "Harry") sameElements indexesOf(listB, "Harry")
答案 1 :(得分:2)
您可以.zip
列表,然后使用.exists
检查是否存在一个等于"Harry"
而另一个不等的元组:
scala> val listA = List("Mary", "Harry", "Marry", "Harry", "Marry")
listA: List[String] = List(Mary, Harry, Marry, Harry, Marry)
scala> val listB = List("Mary", "Harry", "Marry", "Harry", "Marry")
listB: List[String] = List(Mary, Harry, Marry, Harry, Marry)
scala> (listA zip listB).exists { case (a, b) => (a == "Harry" ^ b == "Harry") }
res5: Boolean = false
scala> val listA = List("Mary", "Harry", "Marry", "Harry", "Marry")
listA: List[String] = List(Mary, Harry, Marry, Harry, Marry)
scala> val listB = List("Mary", "Harry", "Marry", "Harry", "Harry") // changed the last one
listB: List[String] = List(Mary, Harry, Marry, Harry, Harry)
scala> (listA zip listB).exists { case (a, b) => (a == "Harry" ^ b == "Harry") }
res6: Boolean = true