복붙노트

[SCALA] 스칼라는 어떻게 목록에 발생 횟수를 셀 수

SCALA

스칼라는 어떻게 목록에 발생 횟수를 셀 수

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

list.count (2) (반환 3) :이처럼 구현하려는.

해결법

  1. ==============================

    1.다른 답변 중 하나의 다소 청소기 버전입니다 :

    다른 답변 중 하나의 다소 청소기 버전입니다 :

    val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
    
    s.groupBy(identity).mapValues(_.size)
    

    원래 순서의 각 항목에 대해 카운트와지도를 제공합니다 :

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

    문제는 특정 항목의 수를 찾는 방법을 묻습니다. 이 방법이 솔루션은 다음과 같이 그 카운트 값에 원하는 요소를 매핑 필요 :

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

    2.스칼라 컬렉션 수 있습니까 : list.count를 (_ == 2)

    스칼라 컬렉션 수 있습니까 : list.count를 (_ == 2)

  3. ==============================

    3.나는 샤 라트 Prabhal과 같은 문제가 있었다, 나는 (나에게 명확) 솔루션을 다른를 가지고 :

    나는 샤 라트 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)
    
  4. ==============================

    4.

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

    제공

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

    신원 기능 내장으로 당신이 (내가 => I) 대체 할 수 있습니다 :

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

    5.

    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))
    
  6. ==============================

    6.저도 같은 문제로 실행하지만, 한 번에 여러 항목을 계산하고 싶었 ..

    저도 같은 문제로 실행하지만, 한 번에 여러 항목을 계산하고 싶었 ..

    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

  7. ==============================

    7.당신이 list.count처럼 사용하려는 경우 (2) 당신은 암시 클래스를 사용하여 구현해야한다.

    당신이 list.count처럼 사용하려는 경우 (2) 당신은 암시 클래스를 사용하여 구현해야한다.

    implicit class Count[T](list: List[T]) {
      def count(n: T): Int = list.count(_ == n)
    }
    
    List(1,2,4,2,4,7,3,2,4).count(2)  // returns 3
    List(1,2,4,2,4,7,3,2,4).count(5)  // returns 0
    
  8. ==============================

    8.스칼라 2.13을 시작으로 groupMapReduce 방법 않는다는 목록을 한 번에 :

    스칼라 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
    

    이:

    이 번역 할 수있는 일의 1 패스 버전입니다 :

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

    9.짧은 답변:

    짧은 답변:

    import scalaz._, Scalaz._
    xs.foldMap(x => Map(x -> 1))
    

    긴 대답 :

    주어진 Scalaz 사용.

    import scalaz._, Scalaz._
    
    val xs = List('a, 'b, 'c, 'c, 'a, 'a, 'b, 'd)
    

    다음 (이하 단순화의 순서로 더 단순화에) 모든 이들의

    xs.map(x => Map(x -> 1)).foldMap(identity)
    xs.map(x => Map(x -> 1)).foldMap()
    xs.map(x => Map(x -> 1)).suml
    xs.map(_ -> 1).foldMap(Map(_))
    xs.foldMap(x => Map(x -> 1))
    

    수율

    Map('b -> 2, 'a -> 3, 'c -> 2, 'd -> 1)
    
  10. ==============================

    10.의도적으로이 사건에 대한 설계 기본 0 값으로지도, (GROUPBY으로 간결하지) 최악의 성능을 보여줍니다 것을주의하는 것이 재미있다

    의도적으로이 사건에 대한 설계 기본 0 값으로지도, (GROUPBY으로 간결하지) 최악의 성능을 보여줍니다 것을주의하는 것이 재미있다

        type Word = String
        type Sentence = Seq[Word]
        type Occurrences = scala.collection.Map[Char, Int]
    
      def woGrouped(w: Word): Occurrences = {
            w.groupBy(c => c).map({case (c, list) => (c -> list.length)})
      }                                               //> woGrouped: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
    
      def woGetElse0Map(w: Word): Occurrences = {
            val map = Map[Char, Int]()
            w.foldLeft(map)((m, c) => m + (c -> (m.getOrElse(c, 0) + 1)) )
      }                                               //> woGetElse0Map: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
    
      def woDeflt0Map(w: Word): Occurrences = {
            val map = Map[Char, Int]().withDefaultValue(0)
            w.foldLeft(map)((m, c) => m + (c -> (m(c) + 1)) )
      }                                               //> woDeflt0Map: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
    
      def dfltHashMap(w: Word): Occurrences = {
            val map = scala.collection.immutable.HashMap[Char, Int]().withDefaultValue(0)
            w.foldLeft(map)((m, c) => m + (c -> (m(c) + 1)) )
        }                                             //> dfltHashMap: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
    
        def mmDef(w: Word): Occurrences = {
            val map = scala.collection.mutable.Map[Char, Int]().withDefaultValue(0)
            w.foldLeft(map)((m, c) => m += (c -> (m(c) + 1)) )
      }                                               //> mmDef: (w: forcomp.threadBug.Word)forcomp.threadBug.Occurrences
    
        val functions = List("grp" -> woGrouped _, "mtbl" -> mmDef _, "else" -> woGetElse0Map _
        , "dfl0" -> woDeflt0Map _, "hash" -> dfltHashMap _
        )                                  //> functions  : List[(String, String => scala.collection.Map[Char,Int])] = Lis
                                                      //| t((grp,<function1>), (mtbl,<function1>), (else,<function1>), (dfl0,<functio
                                                      //| n1>), (hash,<function1>))
    
    
        val len = 100 * 1000                      //> len  : Int = 100000
        def test(len: Int) {
            val data: String = scala.util.Random.alphanumeric.take(len).toList.mkString
            val firstResult = functions.head._2(data)
    
            def run(f: Word => Occurrences): Int = {
                val time1 = System.currentTimeMillis()
                val result= f(data)
                val time2 = (System.currentTimeMillis() - time1)
                assert(result.toSet == firstResult.toSet)
                time2.toInt
            }
    
            def log(results: Seq[Int]) = {
                     ((functions zip results) map {case ((title, _), r) => title + " " + r} mkString " , ")
            }
    
            var groupResults = List.fill(functions.length)(1)
    
            val integrals = for (i <- (1 to 10)) yield {
                val results = functions map (f => (1 to 33).foldLeft(0) ((acc,_) => run(f._2)))
                println (log (results))
                    groupResults = (results zip groupResults) map {case (r, gr) => r + gr}
                    log(groupResults).toUpperCase
            }
    
            integrals foreach println
    
        }                                         //> test: (len: Int)Unit
    
    
        test(len)
        test(len * 2)
    // GRP 14 , mtbl 11 , else 31 , dfl0 36 , hash 34
    // GRP 91 , MTBL 111
    
        println("Done")
        def main(args: Array[String]) {
        }
    

    생산

    grp 5 , mtbl 5 , else 13 , dfl0 17 , hash 17
    grp 3 , mtbl 6 , else 14 , dfl0 16 , hash 16
    grp 3 , mtbl 6 , else 13 , dfl0 17 , hash 15
    grp 4 , mtbl 5 , else 13 , dfl0 15 , hash 16
    grp 23 , mtbl 6 , else 14 , dfl0 15 , hash 16
    grp 5 , mtbl 5 , else 13 , dfl0 16 , hash 17
    grp 4 , mtbl 6 , else 13 , dfl0 16 , hash 16
    grp 4 , mtbl 6 , else 13 , dfl0 17 , hash 15
    grp 3 , mtbl 5 , else 14 , dfl0 16 , hash 16
    grp 3 , mtbl 6 , else 14 , dfl0 16 , hash 16
    GRP 5 , MTBL 5 , ELSE 13 , DFL0 17 , HASH 17
    GRP 8 , MTBL 11 , ELSE 27 , DFL0 33 , HASH 33
    GRP 11 , MTBL 17 , ELSE 40 , DFL0 50 , HASH 48
    GRP 15 , MTBL 22 , ELSE 53 , DFL0 65 , HASH 64
    GRP 38 , MTBL 28 , ELSE 67 , DFL0 80 , HASH 80
    GRP 43 , MTBL 33 , ELSE 80 , DFL0 96 , HASH 97
    GRP 47 , MTBL 39 , ELSE 93 , DFL0 112 , HASH 113
    GRP 51 , MTBL 45 , ELSE 106 , DFL0 129 , HASH 128
    GRP 54 , MTBL 50 , ELSE 120 , DFL0 145 , HASH 144
    GRP 57 , MTBL 56 , ELSE 134 , DFL0 161 , HASH 160
    grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 31
    grp 7 , mtbl 10 , else 28 , dfl0 32 , hash 31
    grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 32
    grp 7 , mtbl 11 , else 28 , dfl0 31 , hash 33
    grp 7 , mtbl 11 , else 28 , dfl0 32 , hash 31
    grp 8 , mtbl 11 , else 28 , dfl0 31 , hash 33
    grp 8 , mtbl 11 , else 29 , dfl0 38 , hash 35
    grp 7 , mtbl 11 , else 28 , dfl0 32 , hash 33
    grp 8 , mtbl 11 , else 32 , dfl0 35 , hash 41
    grp 7 , mtbl 13 , else 28 , dfl0 33 , hash 35
    GRP 7 , MTBL 11 , ELSE 28 , DFL0 31 , HASH 31
    GRP 14 , MTBL 21 , ELSE 56 , DFL0 63 , HASH 62
    GRP 21 , MTBL 32 , ELSE 84 , DFL0 94 , HASH 94
    GRP 28 , MTBL 43 , ELSE 112 , DFL0 125 , HASH 127
    GRP 35 , MTBL 54 , ELSE 140 , DFL0 157 , HASH 158
    GRP 43 , MTBL 65 , ELSE 168 , DFL0 188 , HASH 191
    GRP 51 , MTBL 76 , ELSE 197 , DFL0 226 , HASH 226
    GRP 58 , MTBL 87 , ELSE 225 , DFL0 258 , HASH 259
    GRP 66 , MTBL 98 , ELSE 257 , DFL0 293 , HASH 300
    GRP 73 , MTBL 111 , ELSE 285 , DFL0 326 , HASH 335
    Done
    

    대부분의 간결 GROUPBY도 변경할지도보다 더 빠르다는 것을 호기심!

  11. ==============================

    11.여기에 또 다른 옵션은 다음과 같습니다

    여기에 또 다른 옵션은 다음과 같습니다

    scala> val list = List(1,2,4,2,4,7,3,2,4)
    list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
    
    scala> list.groupBy(x => x) map { case (k,v) => k-> v.length }
    res74: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)
    
  12. ==============================

    12.

    scala> val list = List(1,2,4,2,4,7,3,2,4)
    list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
    
    scala> println(list.filter(_ == 2).size)
    3
    
  13. ==============================

    13.나는 대답은 위의 때문에 여기에보고 문제의 그것을 제안 하나로서 길이 아니라 크기를 사용하여 목록의 크기를하지 않았다.

    나는 대답은 위의 때문에 여기에보고 문제의 그것을 제안 하나로서 길이 아니라 크기를 사용하여 목록의 크기를하지 않았다.

    val list = List("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
    list.groupBy(x=>x).map(t => (t._1, t._2.size))
    
  14. ==============================

    14.고양이를 사용하여

    고양이를 사용하여

    import cats.implicits._
    
    "Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.combineAll
    "Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.foldMap(identity)
    
  15. ==============================

    15.이 시도 작동합니다.

    이 시도 작동합니다.

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

    그것은 3을 반환합니다

  16. from https://stackoverflow.com/questions/11448685/scala-how-can-i-count-the-number-of-occurrences-in-a-list by cc-by-sa and MIT license