LoginSignup
2
1

More than 3 years have passed since last update.

【python】 リスト内の特定の要素の数を取得

Last updated at Posted at 2020-07-14

リストの中に特定の要素がいくつあるかを数える

リストの要素に、ある要素がいくつあるかを数えたいとき、count()が使えます。
また、これは文字列に対しても使えます。

count()

l = [1, 2, 2, 3, 3, 3]
print(l.count(2)) 

# 出力結果: 2
s = 'hello world!'
print(s.count('o'))

# 出力結果: 2

その他

l = [1, 2, 2, 3, 3, 3]
print(len([a for a in l if a == 2]))  # 2
l = [1, 2, 2, 3, 3, 3]
print(sum([a == 2 for a in l]))  # 2

条件にあてはまる要素の数え上げにはこちらで対応できます。

2
1
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
2
1