2015-04-21 9 views
-4

我已經做了我這個代碼遠,但它不與刪除正常工作()..誰能幫助我..如何從列表中刪除的話在Python

''' 
Created on Apr 21, 2015 

@author: Pallavi 
''' 
from pip._vendor.distlib.compat import raw_input 
print ("Enter Query") 
str=raw_input() 

fo = open("stopwords.txt", "r+") 
str1 = fo.read(); 
list=str1.split("\n"); 
fo.close() 
words=str.split(" "); 
for i in range(0,len(words)): 
    for j in range(0,len(list)): 
     if(list[j]==words[i]): 
      print(words[i]) 
      words.remove(words(i)) 

以下是錯誤:

Enter Query 
let them cry try diesd 
let them try 
Traceback (most recent call last): 
    File "C:\Users\Pallavi\workspace\py\src\parser.py", line 17, in <module> 
    if(list[j]==words[i]): 
IndexError: list index out of range 
+4

它應該是'字[I]'而不是'話(我)'。另外,不要調用變量'list'或'str',因爲它們也用於標準類。 (當你遇到問題時,粘貼你的錯誤信息;它通常包含解決方案。) –

+0

我修改了那個,但仍然出現這個錯誤輸入查詢 讓他們哭死嘗試 Traceback(最近一次調用最後一次) : 文件 「C:\用戶\ Pallavi \工作空間\ PY \ SRC \ parser.py」,第17行,在 讓 他們 嘗試 如果(列表[J] ==字[I]): IndexError :列表索引超出範圍 –

+0

那麼,那麼實際顯示錯誤呢?或者你期望什麼和你得到什麼? –

回答

2

你有錯誤(除了我的其他評論)是因爲你修改列表,同時迭代它。但是你在開始的時候會佔用列表的長度,因此,在刪除了一些元素後,就無法訪​​問最後的位置。

我會做這種方式:

words = ['a', 'b', 'a', 'c', 'd'] 
stopwords = ['a', 'c'] 
for word in list(words): # iterating on a copy since removing will mess things up 
    if word in stopwords: 
     words.remove(word) 

一個更Python的方式使用list comprehensions

new_words = [word for word in words if word not in stopwords] 
+0

這是你的工作...... –

+0

它不能正常工作你可以再次檢查它 –