Files
Python_CookBook_repo/1.数据结构与算法/12.找出现最多元素.py

24 lines
726 B
Python
Raw Normal View History

2025-09-10 16:12:45 +08:00
words = ["look", "into", "my", "eyes", "look", "into", "my", "eyes",
"the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
"eyes", "don't", "look", "around", "the", "eyes", "look", "into",
"my", "eyes", "you're", "under"]
# collect里面的Counter库可以帮我们计数
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# Counter的底层是一个字典,是一个DefaultDict,这里处于学习目的把它实现一遍
from collections import defaultdict
def counter(word_list):
counter = defaultdict(int)
for word in word_list:
counter[word] += 1
return counter
print(counter(words))