2017-10-05 53 views
0

一個例子名單信:改變字符串中

eword_list = ["a", "is", "bus", "on", "the"] 
alter_the_list("A bus station is where a bus stops A train station is where a train stops On my desk I have a work station", word_list) 
print("1.", word_list) 

word_list = ["a", 'up', "you", "it", "on", "the", 'is'] 
alter_the_list("It is up to YOU", word_list) 
print("2.", word_list) 

word_list = ["easy", "come", "go"] 
alter_the_list("Easy come easy go go go", word_list) 
print("3.", word_list) 

word_list = ["a", "is", "i", "on"] 
alter_the_list("", word_list) 
print("4.", word_list) 

word_list = ["a", "is", "i", "on", "the"] 
alter_the_list("May your coffee be strong and your Monday be short", word_list) 
print("5.", word_list) 

def alter_the_list(text, word_list): 
    return[text for text in word_list if text in word_list] 

我試圖從單詞的列表,它是文本串在一個單獨的字刪除任何字。在檢查單詞列表中的元素都是小寫字母之前,應該將文本字符串轉換爲小寫字母。字符串中沒有標點符號,單詞參數列表中的每個單詞都是唯一的。我不知道如何解決它。

輸出:

1. ['a', 'is', 'bus', 'on', 'the'] 
2. ['a', 'up', 'you', 'it', 'on', 'the', 'is'] 
3. ['easy', 'come', 'go'] 
4. ['a', 'is', 'i', 'on'] 
5. ['a', 'is', 'i', 'on', 'the'] 

預期:

1. ['the'] 
2. ['a', 'on', 'the'] 
3. [] 
4. ['a', 'is', 'i', 'on'] 
5. ['a', 'is', 'i', 'on', 'the'] 
+0

'list(set(word_list)--set(setence.lower().split() )'。 –

回答

1

我已經做了這樣的:

def alter_the_list(text, word_list): 
    for word in text.lower().split(): 
     if word in word_list: 
      word_list.remove(word) 

text.lower().split()返回text所有空格分隔的標記列表。

關鍵是你需要改變word_list。僅返回新的list是不夠的;您必須使用Python 3's list methods就地修改列表。

0

你的主要問題是你從你的函數返回一個值,但是忽略它。你必須將其保存以某種方式打印出來,如:

word_list = ["easy", "come", "go"] 
word_out = alter_the_list("Easy come easy go go go", word_list) 
print("3.", word_out) 

你印什麼是原來的單詞列表,而不是函數結果。

你忽略文本參數的功能。在列表理解中重用變量名稱作爲循環索引。得到了不同的變量名,如

return[word for word in word_list if word in word_list] 

您還必須涉及您生成列表的邏輯文本。請記住,您在給定的文本中查找而不是的文字。

最重要的是,學習基本的調試。 看到這個可愛的debug博客尋求幫助。

如果沒有其他問題,請學會使用簡單的print語句來顯示變量的值並跟蹤程序執行。

這是否讓你朝着解決方案邁進?

1

如果結果列表的順序不要緊,你可以使用集:

def alter_the_list(text, word_list): 
    word_list[:] = set(word_list).difference(text.lower().split()) 

此功能將更新到位word_list由於分配到列表中片與word_list[:] = ...

+0

這應該是我見過的最快的編輯和downvote。 – mhawke

+0

那麼,我只負責這些行爲的一個** :-)我其實認爲這是一個有用的答案。 +1 –

+0

@ChristianDean:感謝編輯然後:) – mhawke

0

我喜歡@Simon的答案更好,但如果你想在兩個列表解析中做:

def alter_the_list(text, word_list): 
    # Pull out all words found in the word list 
    c = [w for w in word_list for t in text.split() if t == w] 
    # Find the difference of the two lists 
    return [w for w in word_list if w not in c] 
+0

這實際上可以在一個列表中理解:'[word_list中的單詞如果單詞不在setence.lower()。split()]中,它仍然是相當可讀。 –