[英]Removing elements from list in python
我有一個這樣的形狀的清單:
temp5=[]
for i in range(0,len(df)):
temp5.append(df['text'][i].split())
df['each']=temp5
df['each']
結果是這樣的:
現在,我想刪除上一個列表中的某些元素。 我想檢查上一個列表中的每個單詞是否類似於以下列表,將其從中刪除。 第二個列表是這樣的:
stopwords = open('stop_words.txt','r').read().split('\n')
print(stopwords)
現在,我編寫了這段代碼,以從第一個列表中刪除每個列表的相同單詞。 但是我收到的只是一無所有。 你能幫我嗎?
for k in range(0,len(df)):
for j in df['each'][k][:]:
for f in stopwords:
if f==j:
temp6.append(df['each'][k][:].remove(f))
print(temp6)
如注釋中所述, remove
方法將就地刪除,但是如果您想要更多的“ pythonic”,則工作代碼將是
temp5=[]
for i in range(0,len(df)):
temp5.append([x for x in df['text'][i].split() if x not in stopwords])
使用如本問題所述的列表理解 ,它創建了過濾列表。 或者,如果您堅持使用原始數據框作為輸入,那將是
temp5=[]
for i in range(0,len(df)):
temp5.append([x for x in df['each'][i] if x not in stopwords])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.