Python 文字列内で最も多く出現する文字を求める

Document 对象参考手册Python3 実例

Python では、次を使用できますcollections.Counter文字列内の各文字の出現回数を集計し、最も多く出現する文字を見つけます。

実例

from collections import Counter

def most_frequent_letter(s):
    # Counter を使用して各文字の出現回数を集計する
    counter = Counter(s)
    # 最も多く出現する文字を見つける
    most_common = counter.most_common(1)
    return most_common[0][0] if most_common else None

# テスト
s = "hello world"
result = most_frequent_letter(s)
print(f"The most frequent letter in '{s}' is: {result}")

コード解析:

  1. from collections import Counter:インポートCounterクラス。要素の出現回数を集計するために使用します。
  2. counter = Counter(s):作成するCounterオブジェクト。文字列を集計するs内の各文字の出現回数。
  3. most_common = counter.most_common(1):使用するmost_common(1)メソッドで最も多く出現する文字とその回数を取得し、タプルを含むリストを返します。
  4. return most_common[0][0] if most_common else None:最も多く出現する文字を返します。文字列が空の場合は返しますNone。
  5. s = "hello world":テスト用の文字列を定義します。
  6. result = most_frequent_letter(s):関数を呼び出して結果を取得します。
  7. print(f"The most frequent letter in '{s}' is: {result}"):結果を出力します。

出力結果:

The most frequent letter in 'hello world' is: l

Document 对象参考手册Python3 実例

その他の拡張