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}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章