比较两个列表中的项目

blu*_*sky 7 scala

我有两个清单: List(1,1,1) , List(1,0,1)

我想得到以下内容:

  1. 每个元素的计数,包含第一个列表中的1和相应列表中相同位置的0,反之亦然.在上面的例子中,这将是1,0,因为第一个列表在中间位置包含1,而第二个列表在相同位置(中间)包含0.

  2. 每个元素的计数,其中1在第一个列表中,1也在第二个列表中.在上面的例子中,这是两个,因为每个相应的列表中有两个1.我可以使用类List的intersect方法得到它.

我只是在寻找上述第1点的答案.我可以使用迭代方法来计算项目,但是有更实用的方法吗?这是整个代码:

class Similarity {
  def getSimilarity(number1: List[Int], number2: List[Int]) = {
    val num: List[Int] = number1.intersect(number2)
    println("P is " + num.length)
  }
}

object HelloWorld {
  def main(args: Array[String]) {
    val s = new Similarity
    s.getSimilarity(List(1, 1, 1), List(1, 0, 1))
  }
}
Run Code Online (Sandbox Code Playgroud)

Jat*_*tin 11

对于第一个:

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

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

scala> a.zip(b).filter(x => x._1==1 && x._2==0).size
res7: Int = 1
Run Code Online (Sandbox Code Playgroud)

对于第二个:

scala> a.zip(b).filter(x => x._1==1 && x._2==1).size
res7: Int = 2
Run Code Online (Sandbox Code Playgroud)

  • 实际上你可以用`count(predicate)`替换`filter(predicate).size` (8认同)

pag*_*_5b 7

您可以轻松统计所有组合,并将其放在地图中

def getSimilarity(number1 : List[Int] , number2 : List[Int]) = {

  //sorry for the 1-liner, explanation follows 
  val countMap = (number1 zip number2) groupBy (identity) mapValues {_.length}

}

/*
 * Example
 * number1 = List(1,1,0,1,0,0,1)
 * number2 = List(0,1,1,1,0,1,1)
 * 
 * countMap = Map((1,0) -> 1, (1,1) -> 3, (0,1) -> 2, (0,0) -> 1)
 */
Run Code Online (Sandbox Code Playgroud)

诀窍是一个常见的

// zip the elements pairwise

(number1 zip number2) 

/* List((1,0), (1,1), (0,1), (1,1), (0,0), (0,1), (1,1))
 *
 * then group together with the identity function, so pairs
 * with the same elements are grouped together and the key is the pair itself
 */ 

.groupBy(identity) 

/* Map( (1,0) -> List((1,0)), 
 *      (1,1) -> List((1,1), (1,1), (1,1)), 
 *      (0,1) -> List((0,1), (0,1)), 
 *      (0,0) -> List((0,0))
 * )
 *
 * finally you count the pairs mapping the values to the length of each list
 */

.mapValues(_.length)

/* Map( (1,0) -> 1, 
 *      (1,1) -> 3, 
 *      (0,1) -> 2, 
 *      (0,0) -> 1
 * )
Run Code Online (Sandbox Code Playgroud)

然后你需要做的就是在地图上查找