拆分单词后从列表中删除单词:Python

2024-06-16 09:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

List = ['iamcool', 'Noyouarenot'] 
stopwords=['iamcool']

我要做的是从我的列表中删除stowprds。我试着用下面的脚本来实现这一点

query1=List.split()
resultwords  = [word for word in query1 if word not in stopwords]
result = ' '.join(resultwords)
return result

所以我的结果应该是

result =['Noyouarenot']

我收到一个错误

AttributeError: 'list' object has no attribute 'split'

这也是对的,我少了什么小东西,请帮忙。我感谢你的帮助。你知道吗


Tags: in脚本列表forresultlistword单子
2条回答

具有检查stopwords中成员资格条件的列表理解。你知道吗

print [item for item in List if item not in stopwords]

filter

print filter(lambda item: item not in stopwords, List)

或者set操作,你可以参考我关于速度差异的答案here。你知道吗

print list(set(List) - set(stopwords))

输出->;['Noyouarenot']

下面是修复错误的片段:

lst = ['iamcool', 'Noyouarenot']
stopwords = ['iamcool']

resultwords = [word for word in lst if word not in stopwords]
result = ' '.join(resultwords)
print result

另一种可能的解决方案是假设您的输入列表和非索引词列表不关心顺序和重复项:

print " ".join(list(set(lst)-set(stopwords)))

相关问题 更多 >