【问题标题】:What does "[w for w in word_tokens if..." mean in Python? [duplicate]“[w for w in word_tokens if...”在 Python 中是什么意思? [复制]
【发布时间】:2017-08-14 18:10:55
【问题描述】:

我有一个关于 Python 中使用的语法的一般性问题。我对编程很陌生,所以这似乎是一个菜鸟问题,但我使用的是 pythons nltk,其中有一个命令如下所示......

word_tokens = word_tokenize(example_sent)

filtered_sentence = [w for w in word_tokens if not w in stop_words]

filtered_sentence = []

for w in word_tokens:
if w not in stop_words:
    filtered_sentence.append(w)

有人能解释“w for w in word_tokens”背后的逻辑吗? 我已经以多种形式看到了这一点,所以任何人都可以在“X for X in X”中分解这里发生的事情吗?

希望对此处使用的概念进行一些澄清,在此先感谢!

【问题讨论】:

  • 这是一个列表理解。您应该在谷歌上搜索它,因为它可能是一个非常令人困惑的主题,很难用一个答案来解释。这是函数式编程范式的“代表”。

标签: python python-3.x nltk


【解决方案1】:
filtered_sentence = [w for w in word_tokens if not w in stop_words]

相当于:

filtered_sentence = []
for w in word_tokens:
    if not w in stopwords:
        filtered_sentence.append(w)

【讨论】:

    猜你喜欢
    • 2015-03-26
    • 2015-01-05
    • 2017-12-02
    • 2010-11-19
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    相关资源
    最近更新 更多