0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python Counterクラスが便利な件について ~もう自分で数える必要は無い~

Last updated at Posted at 2020-11-08

#概要
これまで、リスト内に要素が何個ずつ含まれているかをチェックするために、リスト要素をfor文で回して、dictに要素・個数の組み合わせをセットしていた。
しかし、collections.Counterクラスを使えば、一行で処理が可能となる。

#これまで(dictでごりごり)

    a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
    b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]

    a_dict = dict()
    b_dict = dict()

    for item in a:
        if item in a_dict:
            a_dict[item] += 1
        else:
            a_dict[item] = 1

    for item in b:
        if item in b_dict:
            b_dict[item] += 1
        else:
            b_dict[item] = 1

    print(a_dict) #{1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
    print(b_dict) #{1: 1, 2: 2, 3: 3, 4: 4, 6: 6}

#Counterクラスを使うと

    from collections import Counter

    a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
    b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]

    a_counter = Counter(a)
    b_counter = Counter(b)
    print(a_counter) #Counter({5: 5, 4: 4, 3: 3, 2: 2, 1: 1})
    print(b_counter) #Counter({6: 6, 4: 4, 3: 3, 2: 2, 1: 1})

#Counterクラスでは、和集合・差集合の演算が可能


    from collections import Counter

    a = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
    b = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]

    a_counter = Counter(a)
    b_counter = Counter(b)

    print(a_counter + b_counter) #Counter({4: 8, 3: 6, 6: 6, 5: 5, 2: 4, 1: 2})
    print(a_counter - b_counter) #Counter({5: 5})

#Counterの内容のソート
直接ソートは出来ないので、以下の様に(個数,キー値)タプルのリストを個数でソートして、さらに(キー値,個数)のリストに戻す様にする。
したがって、ソート結果はタプルのリスト型になる。


    from collections import Counter

    a = ["A", "B", "B", "C", "C", "C", "D", "D", "D", "D", "E", "E", "E", "E", "E"]

    a_counter = Counter(a)

    #昇順ソート
    a_counter_sorted = [(l, k) for k, l in sorted([(j, i) for i, j in a_counter.items()])]
    print(a_counter_sorted) #[('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)]

    #降順ソート
    a_counter_sorted = [(l, k) for k, l in sorted([(j, i) for i, j in a_counter.items()], reverse=True)]
    print(a_counter_sorted) #[('E', 5), ('D', 4), ('C', 3), ('B', 2), ('A', 1)]

#AtCoderでCounterクラスを利用すると簡単に解ける問題

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?