2017-06-05 79 views
0

我想刪除以忽略列表中的重複項。例如,假設函數檢查以「。」結尾的單詞並將它們放入列表中。我想確保重複的單詞不在列表中。刪除列表中的項目

這裏是我迄今爲止

def endwords(sent): 
    list = [] 
    words = sent.split() 
    for word in words: 
     if "." in word: 
      list.append(word) 
     # bottom if statment does not work for some reason. thats the one i am trying to fix  
     if (word == list): 
      list.remove(word) 
    return list  

請注意,我用Python 3

+0

你應該避免使用內置插件的名稱爲您的對象(如'list','dict','str'等) –

回答

2

你怎麼樣檢查,如果這個詞是已經在列表中追加它,像這樣前:

def endwords(sent): 
    wordList = [] 
    words = sent.split() 
    for word in words: 
     if "." in word and word not in wordList: 
      wordList.append(word) 
    return wordList 

您正在嘗試檢查是否word == list,但是如果該單詞與整個列表相同,則顯示該單詞。要檢查一個元素是否在python容器中,可以使用in關鍵字。或者,要檢查某件物品是否不在容器中,可以使用not in

另一種選擇是使用一組:

def endwords(sent): 
    wordSet = set() 
    words = sent.split() 
    for word in words: 
     if "." in word: 
      wordSet.add(word) 
    return wordSet 

使事情乾淨了一點,這裏是使用設置理解一個版本:

def endwords(sent): 
    return {word for word in sent.split() if '.' in word} 

如果你想獲得一個名單出來你可以這樣做:

def endwords(sent): 
    return list({word for word in sent.split() if '.' in word}) 

既然你說你的問題,你想檢查是否噸他的詞以結束後,你可能也想使用的endsWith()函數像這樣「」:

def endwords(sent): 
    return list({word for word in sent.split() if word.endswith('.')}) 
0

您可以添加一個樣本法官的提問。

def endwords(sent): 
    list = [] 
    words = sent.split() 
    for word in words: 
     if "." in word: 
      if word not in list: 
       list.append(word) 
     # bottom if statment does not work for some reason. thats the one i am trying to fix 

    return list 
0

爲什麼不使用set?

def endwords(sent): 
    my_list = set() 
    words = sent.split() 
    for word in words: 
     if "." in word: 
      my_list.add(word) 
    return my_list 
0

的更簡潔的方式,將使用列表理解的事,那就是

my_list = [word for word in words if '.' in word] 

,並保證元素不重複,只是使用set

my_list = set(my_list) # No more duplicated values 
2

語句後

list = [] 

你不能使用內置list class和明白,你可以花大約一個小時左右,這就是爲什麼我們要避免的內置插件的名稱,我們的對象。

更多在this answer


函數檢查與一個 '' 結尾的單詞。「」

聲明如果

"." in word 

檢查word包含點符號(如"." in "sample.text"將好的工作,而它根本不點結尾),如果你需要檢查它與點結束 - 使用str.endswith方法。


我想,以確保重複的話不要在列表中去。

只是確保在存儲尚未存儲的文件之前。


最後,我們可以寫

def endwords(sent, end='.'): 
    unique_words = [] 
    words = sent.split() 
    for word in words: 
     if word.endswith(end) and word not in unique_words: 
      unique_words.append(word) 
    return unique_words 

測試

>>>sent = ' '.join(['some.', 'oth.er'] * 10) 
>>>unique_words = endwords(sent) 
>>>unique_words 
['some.'] 

PS

如果順序並不重要 - 使用set,很會照顧重複的(僅適用可拆分類型,str可哈希):

def endwords(sent, end='.'): 
    unique_words = set() 
    words = sent.split() 
    for word in words: 
     if word.endswith(end) and word not in unique_words: 
      unique_words.add(word) 
    return unique_words 

或一套理解

def endwords(sent, end='.'): 
    words = sent.split() 
    return {word for word in words if word.endswith(end)}