python - 从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)
解决方案
正如评论中提到的,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])
推荐阅读
- javascript - Vuex getter 不更新状态变化
- python - 无法在 Keras 预训练模型中生成张量板
- c++ - 您如何覆盖要与类指针一起使用的运算符?
- pandas - Pandas - 尝试通过使用 Pandas 读取文件来保存一组文件,但只保存最新的文件
- robots.txt - robots.txt:通配符是否也意味着没有字符?
- spring - 多部分 REST 操作的客户端代码
- reactjs - { apollo-client, react, grapgql } 处理多重加载的好方法是什么?
- dart - 如何使用多个列表视图构建器滚动页面
- abap - 调用不带命名参数的动态方法
- javascript - 如何获取json数组中多个键的键并操作它们的数据?