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