【发布时间】:2016-01-05 11:52:28
【问题描述】:
我在 python 中有一个列表列表,里面充满了文本。这就像从每个文档中设置单词。因此,对于每个文档,我都有一个列表,然后是所有文档的列表。
所有列表只包含唯一的单词。 我的目的是计算完整文档中每个单词的出现次数。我可以使用以下代码成功地做到这一点:
for x in texts_list:
for l in x:
if l in term_appearance:
term_appearance[l] += 1
else:
term_appearance[l] = 1
但我想使用字典理解来做同样的事情。这是第一次,我正在尝试编写字典理解并使用 stackoverflow 中以前的现有帖子,我已经能够编写以下内容:
from collections import defaultdict
term_appearance = defaultdict(int)
{{term_appearance[l] : term_appearance[l] + 1 if l else term_appearance[l] : 1 for l in x} for x in texts_list}
上一篇供参考:
Simple syntax error in Python if else dict comprehension
按照上面帖子的建议,我还使用了以下代码:
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
上面的代码成功生成了空列表,但最终抛出了以下回溯:
[]
[]
[]
[]
Traceback (most recent call last):
File "term_count_fltr.py", line 28, in <module>
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
File "term_count_fltr.py", line 28, in <setcomp>
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
TypeError: unhashable type: 'dict'
如果能帮助我提高当前的理解,我们将不胜感激。
看了上面的错误,我也试过了
[{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list]
运行没有任何错误,但输出仅为空列表。
【问题讨论】:
-
祝你好运...这是一个想法,默认字典将默认为零,这意味着您可能不需要 if-else 部分。
标签: python list python-2.7 dictionary dictionary-comprehension