簡體   English   中英

有人可以幫我理解python中的循環嗎

[英]Can someone help me understand this for loop in python

我正在嘗試從其他來源回收此代碼,但是在理解第二行中的for循環時遇到了麻煩。 有人可以說清楚此行title = [x for x in title if x not in stopWords]在做什么? stopWords是單詞列表。

def title_score(title, sentence):

    title = [x for x in title if x not in stopWords]
    count = 0.0
    for word in sentence:
        if (word not in stopWords and word in title):
            count += 1.0

    if len(title) == 0:
        return 0.0

    return count/len(title)
[x for x in title if x not in stopWords]

這是一個列表理解。 這意味着構造一個title中所有項目的列表(即x for x in title位中x for x in title ),這些項目也不在stopWords (按if x not in stopWords位)。


您可以通過以下片段看到類似的效果。 第一個創建一個包含范圍0..9的所有數字的列表:

>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

第二個語句添加了if子句,僅包含奇數:

>>> [x for x in range(10) if x % 2 != 0]
[1, 3, 5, 7, 9]

這也許是一個更好的示例,與您的代碼更緊密地結合在一起:

>>> stopWords = "and all but if of the".split() ; stopWords
['and', 'all', 'but', 'if', 'of', 'the']

>>> title = "the sum of all fears".split() ; title
['the', 'sum', 'of', 'all', 'fears']

>>> [x for x in title]
['the', 'sum', 'of', 'all', 'fears']

>>> [x for x in title if x not in stopWords]
['sum', 'fears']

在那里,您可以看到在最后一步中刪除了“噪音”字樣。

好吧,他們說python就像可運行的偽代碼,我想這適用於這里。 它正在創建一個列表並將標題中的每個項目都放入其中,而該項目不在stopWords中

這是一個列表理解,等效於以下循環:

newtitle = []
for x in title:
    if x not in stopwords;
        newtitle.append(x)
title = newtitle

換句話說,如果單詞也出現在stopwords詞中,它將有效地從title 刪除所有單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM