LoginSignup
0
0

More than 3 years have passed since last update.

[python] リストの特定の要素がいくつ含まれるかをカウントする

Posted at

背景

ある要素がリスト内にいくつ含まれるのかを知りたいと思ったが、collections.Counterだと要らないのも出てきちゃうなぁと思い、ググってcountメソッドの存在を知った(恥)。

結論

どれか1つ特定の要素のカウントを知りたい場合

some_list = ['foo', 'bar', 'baz', 'bar', 'qux', 'bar', 'bar']
print(some_list.count('bar'))
# 4

複数の要素のカウントを知りたい場合

from collections import Counter

some_list = ['foo', 'bar', 'baz', 'bar', 'qux', 'bar', 'bar']
print(Counter(some_list))
# Counter({'bar': 4, 'foo': 1, 'baz': 1, 'qux': 1})
print(Counter(some_list)['bar'])
# 4

collections.Counterクラス(dictのサブクラス)として得られます。

print(issubclass(type(dict(Counter(some_list))), dict))
# True
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