[scala] Scala 목록에서 발생 횟수를 어떻게 계산할 수 있습니까?

val list = List(1,2,4,2,4,7,3,2,4)

다음과 같이 구현하고 싶습니다 : list.count(2)(3을 반환합니다).



답변

다른 답변 중 하나의 다소 깨끗한 버전은 다음과 같습니다.

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")

s.groupBy(identity).mapValues(_.size)

Map원래 시퀀스의 각 항목에 대한 개수와 함께 제공 :

Map(banana -> 1, oranges -> 3, apple -> 3)

질문은 특정 항목의 개수를 찾는 방법을 묻습니다. 이 방법을 사용하면 솔루션은 원하는 요소를 다음과 같이 개수 값에 매핑해야합니다.

s.groupBy(identity).mapValues(_.size)("apple")


답변

scala 컬렉션에는 count다음 이 있습니다 .list.count(_ == 2)


답변

나는 Sharath Prabhal과 같은 문제가 있었고 또 다른 (더 명확한) 해결책이 있습니다.

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(l => l).map(t => (t._1, t._2.length))

결과적으로 :

Map(banana -> 1, oranges -> 3, apple -> 3)


답변

list.groupBy(i=>i).mapValues(_.size)

준다

Map[Int, Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)

(i=>i)내장 identity함수로 바꿀 수 있습니다 .

list.groupBy(identity).mapValues(_.size)


답변

val list = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
// Using the provided count method this would yield the occurrences of each value in the list:
l map(x => l.count(_ == x))

List[Int] = List(1, 3, 3, 3, 3, 1, 1, 3, 3)
// This will yield a list of pairs where the first number is the number from the original list and the second number represents how often the first number occurs in the list:
l map(x => (x, l.count(_ == x)))
// outputs => List[(Int, Int)] = List((1,1), (2,3), (4,3), (2,3), (4,3), (7,1), (3,1), (2,3), (4,3))


답변

시작 Scala 2.13하면 groupMapReduce 메서드가 목록을 한 번에 통과합니다.

// val seq = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
seq.groupMapReduce(identity)(_ => 1)(_ + _)
// immutable.Map[String,Int] = Map(banana -> 1, oranges -> 3, apple -> 3)
seq.groupMapReduce(identity)(_ => 1)(_ + _)("apple")
// Int = 3

이:

  • groupS리스트 엘리먼트 (그룹 부 그룹 의 MapReduce)

  • maps 각 그룹화 된 값 발생을 1 ( Map Reduce 그룹의 일부 매핑 )

  • reduces 값 _ + _을 합산하여 값 그룹 ( ) 내의 값 ( groupMap Reduce의 일부를 줄임 ).

다음 으로 번역 할 수있는 내용의 원 패스 버전 입니다.

seq.groupBy(identity).mapValues(_.map(_ => 1).reduce(_ + _))


답변

같은 문제가 발생했지만 한 번에 여러 항목을 계산하고 싶었습니다 ..

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.foldLeft(Map.empty[String, Int]) { (m, x) => m + ((x, m.getOrElse(x, 0) + 1)) }
res1: scala.collection.immutable.Map[String,Int] = Map(apple -> 3, oranges -> 3, banana -> 1)

https://gist.github.com/sharathprabhal/6890475