什么';在python中循环列表并生成具有dict理解的词典的正确方法是什么?
什么';在python中循环列表并生成具有dict理解的词典的正确方法是什么?,python,dictionary,Python,Dictionary,testWords是一个包含单词的列表setTestWords是与集合相同的列表。我想创建一个字典,其中我将使用单词作为键,计数作为值。我也在用。计数 示例输出如下所示: >>> dictTestWordsCount[:2] >>> {'hi': 22, 'hello': 99} 这是我正在使用的代码,但它似乎每次都会使我的笔记本崩溃 l = {x: testWords.count(x) for x in setTestwords} 不确定是什么原因导致你
testWords
是一个包含单词的列表setTestWords
是与集合相同的列表。我想创建一个字典,其中我将使用单词作为键,计数作为值。我也在用。计数
示例输出如下所示:
>>> dictTestWordsCount[:2]
>>> {'hi': 22, 'hello': 99}
这是我正在使用的代码,但它似乎每次都会使我的笔记本崩溃
l = {x: testWords.count(x) for x in setTestwords}
不确定是什么原因导致你的笔记本崩溃
In [62]: txt = "the quick red fox jumped over the lazy brown dog"
In [63]: testWords = txt.split()
In [64]: setTestWords = set(testWords)
In [65]: {x:testWords.count(x) for x in setTestWords}
Out[65]:
{'brown': 1,
'dog': 1,
'fox': 1,
'jumped': 1,
'lazy': 1,
'over': 1,
'quick': 1,
'red': 1,
'the': 2}
或者更好地使用
collection.defaultdict
from collections import defaultdict
d = defaultdict(int)
for word in txt.split():
d[word]+=1
print(d)
defaultdict(int,
{'brown': 1,
'dog': 1,
'fox': 1,
'jumped': 1,
'lazy': 1,
'over': 1,
'quick': 1,
'red': 1,
'the': 2})
collections.Counter(testWords)
这是一个作业,我清楚地告诉了我想如何解决这个问题:使用.count和dict理解。你有什么错误?或者它只是需要很长时间才能运行?什么是dicttestwordscont[:2]
?切片一个dict?是的,加载时间太长了。但这是正确的代码还是我遗漏了什么。