【问题标题】:Turning Python short form for loop into long form [duplicate]将Python短形式for循环转换为长形式[重复]
【发布时间】:2018-09-06 13:20:10
【问题描述】:

我从https://stevenloria.com/tf-idf/得到这行代码

scores = {word: tfidf(word, blob, bloblist) for word in blob.words}

tfidf函数在哪里:

import math
from textblob import TextBlob as tb

def tf(word, blob):
    return blob.words.count(word) / len(blob.words)

def n_containing(word, bloblist):
    return sum(1 for blob in bloblist if word in blob.words)

def idf(word, bloblist):
    return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
    return tf(word, blob) * idf(word, bloblist)

为了更好地理解这个过程,我想把速记循环变成一个看起来很普通的“for”循环。

这是正确的吗?

scores = []
for word in blob.words:
    scores.append(tfidf(word, blob, bloblist))

另外,写短形式的for循环有什么好处?

【问题讨论】:

  • 原代码行是字典推导,不是列表推导,你可以通过花括号和key:value 对来判断

标签: python


【解决方案1】:

这是正确的吗?

该代码将为您提供一个列表,但您的原始代码会生成一个字典。相反,请尝试:

scores = {}
for word in blob.words:
    scores[word] = tfidf(word, blob, bloblist)

另外,写短形式的for循环有什么好处?

列表推导(和字典推导等)的主要优点是它们比长形式的等价物短。

【讨论】:

  • 根据 cmets 中的链接更短(更快)
【解决方案2】:

这些被称为comprehensions(示例是最常见的情况,列表解析,尽管这是字典解析)。

它们通常更简单且更具可读性,但如果您发现它们令人困惑,那么按照您的方式写出来完全一样,只是有一个区别

scores = {}
for word in blob.words:
    scores[word] = (tfidf(word, blob, bloblist))

【讨论】:

  • 我认为字典的关键字(词)不应该被引用。
  • 好点。固定。
猜你喜欢
  • 2015-12-04
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
相关资源
最近更新 更多