我想编写一些测试来分析python中不同操作的效率,即字典理解和字典生成器的比较。Python:使用dict理解/生成器计算列表中的事件
为了测试这个,我想我会尝试一个简单的例子:使用字典计算列表中的单词数量。
现在我知道你可以使用collections.Counter
(根据这里的答案:How can I count the occurrences of a list item in Python?)来做到这一点,但我的目标是测试内存的性能。
一个“长手”的方法是在基本循环中完成。
from pprint import pprint
# Read in some text to create example data
with open('text.txt') as f:
words = f.read().split()
dict1 = {}
for w in words:
if not dict1.get(w):
dict1[w] = 1
else:
dict1[w] += 1
pprint(dict1)
结果:
{'a': 62,
'aback': 1,
'able': 1,
'abolished': 2,
'about': 6,
'accept': 1,
'accepted': 1,
'accord': 1,
'according': 1,
'across': 1,
...
然后我有点卡住试图做同样的字典解析:
dict2 = { w: 1 if not dict2.get(w) else dict2.get(w) + 1
for w in words }
我得到了一个错误:
NameError: global name 'dict2' is not defined
我试着定义前面的字典:
dict2 = {}
dict2 = { w: 1 if not dict2.get(w) else dict2.get(w) + 1
for w in words }
pprint(dict2)
但当然计数都设置为1:
{'a': 1,
'aback': 1,
'able': 1,
'abolished': 1,
'about': 1,
'accept': 1,
'accepted': 1,
'accord': 1,
'according': 1,
'across': 1,
...
我也有类似的问题,字典理解:
dict3 = dict((w, 1 if not dict2.get(w) else dict2.get(w) + 1)
for w in words)
所以我的问题是:我怎么能最有效地使用字典理解/生成器来计算列表中出现的次数?
更新:@Rawing提出了一种替代方法{word:words.count(word) for word in set(words)}
,但这将绕过我试图测试的机制。
'dict2'是空的,如果第一个地方就是你得到那个结果的原因。原因是你在检查'dict2.get(w)'时不要在'dict2'中插入结果。我不知道你是否可以用字典理解来解决这个问题,因为你必须存储计数。 – badc0re 2014-11-04 09:34:23
我认为这样做的方式是'{单词:words.count(单词)在单词(单词)}',但我怀疑它是有效的。 – 2014-11-04 09:49:52
@ badc0re是的,我想你可能是对的。也许我需要提出一个更好的测试例子。我会看看是否有其他人有任何想法。谢谢你的帮助。 – 2014-11-04 09:50:01