Если вы хотите иметь всех символов с максимальным количеством отсчетов, то вы можете сделать вариацию на одну из двух предложенных идей:
import heapq # Helps finding the n largest counts
import collections
def find_max_counts(sequence):
"""
Returns an iterator that produces the (element, count)s with the
highest number of occurrences in the given sequence.
In addition, the elements are sorted.
"""
if len(sequence) == 0:
raise StopIteration
counter = collections.defaultdict(int)
for elmt in sequence:
counter[elmt] += 1
counts_heap = [
(-count, elmt) # The largest elmt counts are the smallest elmts
for (elmt, count) in counter.iteritems()]
heapq.heapify(counts_heap)
highest_count = counts_heap[0][0]
while True:
try:
(opp_count, elmt) = heapq.heappop(counts_heap)
except IndexError:
raise StopIteration
if opp_count != highest_count:
raise StopIteration
yield (elmt, -opp_count)
for (letter, count) in find_max_counts('balloon'):
print (letter, count)
for (word, count) in find_max_counts(['he', 'lkj', 'he', 'll', 'll']):
print (word, count)
ЭтоВыход, например:
lebigot@weinberg /tmp % python count.py
('l', 2)
('o', 2)
('he', 2)
('ll', 2)
Это работает с любой последовательностью: слова, но также ['привет', 'привет', 'добрый день], например.
heapq
структура очень эффективна при поиске мельчайших элементов последовательности без ее полной сортировки.С другой стороны, поскольку в алфавите не так много букв, вы, вероятно, также можете пробежаться по отсортированному списку отсчетов до тех пор, пока максимальный отсчет больше не будет найден, без каких-либо серьезных потерь в скорости.