gpt4 book ai didi

python - 字典理解没有按预期进行

转载 作者:行者123 更新时间:2023-11-30 23:09:49 24 4
gpt4 key购买 nike

def tf(tokens):
""" Compute TF
Args:
tokens (list of str): input list of tokens from tokenize
Returns:
dictionary: a dictionary of tokens to its TF values
"""
li = {}
total = len(tokens)
li = {token: 1 if not token in li else li[token] + 1 for token in tokens }
return {token: li[token]/ float(total) for token in li}

基本上,我想要一个字典,其中标记是键,值是该标记在标记列表中的频率。

我希望我的理解能够检查 token 是否已经在 li 中。如果只是将其值增加 1,如果不是,则创建它并将其值设置为 1。

出于某种原因,每个键的最终值都是 (1),无论它在标记列表中出现多少次。

你能帮我看看为什么会发生这种情况吗?

我可以用循环解决它,但我想掌握字典理解。

非常感谢!

最佳答案

诸如列表/字典理解之类的理解表达式是构建器表达式,并且在完全评估表达式之前不会构造对象。随后将符号名称分配给生成的字典的引用。

在您的特定示例中,您引用的是符号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

关于python - 字典理解没有按预期进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com