【Python入門】list.count()の使い方

python

「リストの中に同じ値がいくつあるか知りたい」「特定の値が何回出てきたかを調べたい」──そんなときに便利なのが、Pythonのcount()メソッドです。

このメソッドを使えば、ループや複雑な処理を使わずに簡単に回数を数えることができます。

この記事では、list.count()の基本的な使い方から活用例まで、初心者向けにわかりやすく説明します。


スポンサーリンク

count()の基本的な使い方

書き方

リスト.count(数えたい値)

特徴

  • 指定した値が何回登場するかを返す
  • 戻り値は数字(整数)

使用例

# フルーツのリストを作成
fruits = ["りんご", "バナナ", "りんご", "みかん"]

# "りんご"の数を数える
apple_count = fruits.count("りんご")

# 結果を確認
print(apple_count)  # 2

いろいろなデータで使ってみよう

数字のリストで使う

# 数字のリストを作成
numbers = [1, 2, 3, 2, 4, 2]

# 2がいくつあるか数える
count_of_two = numbers.count(2)
print(count_of_two)  # 3

文字のリストで使う

# 文字のリストを作成
answers = ["はい", "いいえ", "はい", "はい"]

# "はい"の数を数える
yes_count = answers.count("はい")
print(yes_count)  # 3

組み合わせデータで使う

# ペアのデータを作成
pairs = [("A", 1), ("B", 2), ("A", 1), ("C", 3)]

# ("A", 1)のペアがいくつあるか数える
pair_count = pairs.count(("A", 1))
print(pair_count)  # 2

ポイント: count()は数字、文字、ペアなど、いろいろなデータに使えます。


count()の便利な使い方

例1:一番多く出てくる値を見つける

# 好きな色のアンケート結果
colors = ["赤", "青", "赤", "緑", "赤", "青"]

# どの色が一番人気か調べる
unique_colors = set(colors)  # 重複を取り除く
most_popular = max(unique_colors, key=colors.count)

print(f"一番人気の色:{most_popular}")  # 一番人気の色:赤

例2:同じ値があるかどうか調べる

# 出席番号のリスト
student_numbers = [1, 2, 3, 2, 4]

# 重複があるかチェック
has_duplicate = False
for num in student_numbers:
    if student_numbers.count(num) > 1:
        has_duplicate = True
        break

if has_duplicate:
    print("同じ番号が複数あります")
else:
    print("すべて違う番号です")

例3:1回だけ出てくる値を見つける

# テストの点数
scores = [85, 90, 85, 78, 90, 92]

# 1回だけ出てくる点数を見つける
unique_scores = []
for score in scores:
    if scores.count(score) == 1:
        unique_scores.append(score)

print(f"1回だけの点数:{unique_scores}")  # [78, 92]

実際に使える例

例1:アンケート結果を集計

# 好きな季節のアンケート
seasons = ["春", "夏", "春", "秋", "冬", "春", "夏"]

# 各季節の票数を集計
spring_votes = seasons.count("春")
summer_votes = seasons.count("夏")
autumn_votes = seasons.count("秋")
winter_votes = seasons.count("冬")

print("=== アンケート結果 ===")
print(f"春:{spring_votes}票")
print(f"夏:{summer_votes}票")
print(f"秋:{autumn_votes}票")
print(f"冬:{winter_votes}票")

例2:出席回数をチェック

# 1週間の出席記録(○:出席、×:欠席)
attendance = ["○", "○", "×", "○", "○", "○", "×"]

# 出席回数と欠席回数を数える
present_days = attendance.count("○")
absent_days = attendance.count("×")

print(f"出席日数:{present_days}日")
print(f"欠席日数:{absent_days}日")

# 出席率を計算
total_days = len(attendance)
attendance_rate = (present_days / total_days) * 100
print(f"出席率:{attendance_rate:.1f}%")

例3:ゲームのスコア分析

# ゲームの結果(勝ち、負け、引き分け)
game_results = ["勝ち", "負け", "勝ち", "勝ち", "引き分け", "負け", "勝ち"]

# 各結果の回数を数える
wins = game_results.count("勝ち")
losses = game_results.count("負け")
draws = game_results.count("引き分け")

print("=== ゲーム戦績 ===")
print(f"勝利:{wins}回")
print(f"敗北:{losses}回")
print(f"引き分け:{draws}回")

# 勝率を計算
total_games = len(game_results)
win_rate = (wins / total_games) * 100
print(f"勝率:{win_rate:.1f}%")

count()を使うときの注意点

注意点1:完全に一致する値だけを数える

# リストの中にリストがある場合
data = [[1, 2], [3, 4], [1, 2], [1, 3]]

# [1, 2]と完全に一致するものだけ数える
count_result = data.count([1, 2])
print(count_result)  # 2([1, 3]は数えない)

注意点2:大文字と小文字は区別される

# 大文字と小文字が混じったリスト
words = ["Apple", "apple", "APPLE", "apple"]

# 小文字の"apple"だけ数える
lowercase_count = words.count("apple")
print(lowercase_count)  # 2

# 大文字の"APPLE"だけ数える
uppercase_count = words.count("APPLE")
print(uppercase_count)  # 1

注意点3:データが多いと時間がかかる

# データが非常に多い場合は時間がかかることがある
# そんなときは collections.Counter を使うと良い

from collections import Counter

# 大量のデータ例
large_data = ["A"] * 10000 + ["B"] * 5000 + ["C"] * 3000

# Counter を使った方が速い
counter = Counter(large_data)
print(counter["A"])  # 10000

# 通常のcount()でも動くが、データが多いと遅い
# count_A = large_data.count("A")  # 時間がかかる

まとめ

list.count()は、Pythonで最も簡単に値の出現回数を調べる方法です。

特定の値が何回出てくるか知りたいときは、迷わず使える便利なメソッドです。

この記事のポイント

  • リスト.count(値)で指定した値の出現回数がわかる
  • 数字、文字、ペアなど、いろいろなデータに使える
  • アンケート集計、重複チェックなど、応用例が豊富
  • 大量のデータではCounterを使うとより効率的

コメント

タイトルとURLをコピーしました