方式一:
原理:創建一個新的空字典,用循環的方式來獲取列表中的每一個元素,判斷獲取的元素是否存在字典中的key,如果不存在的話,將元素作爲key,值爲列表中元素的count
# 字典方法
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
dict1 = {}
for i in words:
if i not in dict1.keys():
dict1[i] = words.count(i)
print(dict1)
運行結果:
{'my': 2, 'skills': 2, 'are': 2, 'poor': 3, 'I': 2, 'am': 1, 'need': 1, 'more': 1, 'ability': 1, 'so': 1}
方式二
原理:使用setdefault函數
,setdefault()函數
,如果鍵不存在於字典中,將會添加鍵並將值設爲默認值。
打個比方,我們要查找的這個鍵不在字典中,我們先將它置爲0
,然後再加1
,再查找到這個鍵的時候,這個時候它是存在這個字典裏面的,故這個setdefault函數
不生效,然後我們再把次數加1
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
d = dict()
for item in words:
# setdefault()函數,如果鍵不存在於字典中,將會添加鍵並將值設爲默認值
d[item] = d.setdefault(item, 0) + 1
print(d)
運行結果:
{'my': 2, 'skills': 2, 'are': 2, 'poor': 3, 'I': 2, 'am': 1, 'need': 1, 'more': 1, 'ability': 1, 'so': 1}
方式三
原理:使用collections模塊
的Counter類
這個模塊很強大,尤其是這個類。他可以直接幫我們計數,然後再幫我們排序好。從大到小
from collections import Counter
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
collection_words = Counter(words)
print(collection_words)
print(type(collection_words))
運行結果:
Counter({'poor': 3, 'my': 2, 'skills': 2, 'are': 2, 'I': 2, 'am': 1, 'need': 1, 'more': 1, 'ability': 1, 'so': 1})
<class 'collections.Counter'>
還可以輸出頻率最大的n
個元素,類型爲list
most_counterNum = collection_words.most_common(3)
print(most_counterNum)
print(type(most_counterNum))
運行結果:
[('poor', 3), ('my', 2), ('skills', 2)]
<class 'list'>
附
ounter類
支持collections.Counter類型
的相加和相減
也就是用Counter(words)
之後,這個類型是可以相加減的,只支持相加減
例子:
print(collection_words + collection_words)
這裏要注意:不能爲了圖方便進行collection_words * 2
,因爲類型不同,2
爲int
,故不能進行運算
運行結果:
Counter({'poor': 6, 'my': 4, 'skills': 4, 'are': 4, 'I': 4, 'am': 2, 'need': 2, 'more': 2, 'ability': 2, 'so': 2})
如果筆者有其他的方法,會慢慢往文章裏面填寫,感謝