首页 > 解决方案 > 从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)

在此处输入图像描述

现在我编写了这段代码来从第一个列表中删除每个列表中的相同单词。但我收到的只是NONE。你能帮我吗?

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)

标签: pythonpython-3.x

解决方案


正如评论中提到的,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])

推荐阅读