2025-09-10:仓库迁移
This commit is contained in:
24
1.数据结构与算法/12.找出现最多元素.py
Normal file
24
1.数据结构与算法/12.找出现最多元素.py
Normal file
@@ -0,0 +1,24 @@
|
||||
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))
|
||||
|
Reference in New Issue
Block a user