Python字典

在leetcode上刷題的時候,經常需要使用統計元素個數,例如
  • words = [“a”,“b”,“c”,“d”,“a”,“c”,“r”]
  • 統計列表words中每個元素及其出現的次數
words = ["a","b","c","d","a","c","r"]

#方法1,用Counter
from collections import Counter
words_dict_1 = Counter(words)

#方法2,用字典
words_dict_2 = {}
for word in words:
	#當word不在words_dict_2中的時候,會出現KeyError,所以要單獨判斷
	if word not in words_dict_2:
		words_dict_2[word] = 1
	else:
		words_dict_2[word] += 1
		
#方法3,用默認字典
words_dict_3 = collections.defaultdict(int)
for word in words:
	#words_dict_3是默認字典,且裏面是int,所以當key不在字典中時,返回int的默認值,是0
	words_dict_3[word] += 1

#方法4,用字典+get方法
words_dict_4 = {}
for word in words:
	#get方法,當key不在字典中時,默認返回None,不過這裏將默認值改爲了0,即key不在字典中時,返回0
	words_dict_4[word] = words_dict_4.get(word,0) + 1



print(words_dict_1==words_dict_2==words_dict_3==words_dict_4)
#True
print(words_dict_2)
#{'a': 2, 'c': 2, 'b': 1, 'r': 1, 'd': 1}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章