我有一个单词列表
words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one',
'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']
,并且需要使用字典来计算单词的出现次数。
word_counts = {'two':2, 'one':3, 'forks.':1, 'knife.':2, \
'glasses.':2, 'plate.':1, 'naptkin.':1, 'his':2}
我将如何去做?感谢您的帮助!
答案 0 :(得分:3)
Entity Framework Core 3 Preview 7
答案 1 :(得分:0)
words = ['two', 'forks.', 'one', 'knife.', 'two', 'glasses.','one',
'plate.', 'one', 'naptkin.', 'his,' 'glasses.', 'his', 'knife.']
d = {}
for w in words:
if w in d.keys():
d[w] += 1
else:
d[w] = 1
print(d)
答案 2 :(得分:0)
第一个解决方案与Francky_V相似,但是使用.setdefault()
方法。例如:
>>> d = {}
>>> d.setdefault('two', 0) # 'two' is not in d, we can set it
0
>>> d.setdefault('two', 1000) # 'two' is now in d, we cannot set it, returns current value
0
因此,解决方案:
d = {}
for word in words:
d.setdefault(word, 0)
d[word] += 1
第二种解决方案利用了collections.defaultdict
:
import collections
d = collections.defaultdict(int)
for word in words:
d[word] += 1
之所以可行,是因为d
是defaultdict
的{{1}}值。我们第一次提到int
时,该值会自动设置为d[word]
。
当然,0
是最好的解决方案,因为该类是为此目的而构建的。