像列表/字典理解这样的理解表达式是一个构建器表达式,并且该对象在表达式完全评估之前不会构造。在符号名称后面跟随生成字典的引用。
在您的特定示例中,您指的是符号li
,它指的是对象空字典。所以表达式的评估过程中,li
继续指向一个空的字典这意味着,字典理解,可以等效写成
li = {token: 1 if not token in {} else l{}[token] + 1 for token in tokens }
或简化为成员测试上一个空的字典永远是假的
li = {token: 1 for token in tokens }
您需要的是已有的库实用程序或基于状态的解决方案。
幸运的是,标准库collections提供了一个名为counter函数的编写和为此而设计的
这只会您的功能
def tf(tokens):
from collections import Counter
""" Compute TF
Args:
tokens (list of str): input list of tokens from tokenize
Returns:
dictionary: a dictionary of tokens to its TF values
"""
return Counter(tokens)
基于状态的解决方案只需要为每一个外部计数器独特发生
def tf(tokens):
from collections import defaultdict
""" Compute TF
Args:
tokens (list of str): input list of tokens from tokenize
Returns:
dictionary: a dictionary of tokens to its TF values
"""
counter = defaultdict(int)
for token in tokens:
counter[token] += 1
return counter
或者如果您不打算使用defaultdict
def tf(tokens):
from collections import defaultdict
""" Compute TF
Args:
tokens (list of str): input list of tokens from tokenize
Returns:
dictionary: a dictionary of tokens to its TF values
"""
counter = {}
for token in tokens:
counter[token] = counter.get(token, 0) + 1
return counter
'itertools.Counter()object'?我认为你的意思是'collections.Counter()' – Abhijit
@Ahhijit:我当然了。呃,甚至不知道为什么Chrome自动完成URL,我以前一定犯过错误。关闭网站搜索引擎! –
@Abhijit:bingo,[用变量名称键添加项到词典python](https://stackoverflow.com/a/12732835)已更正。 –