我有一个这样的列表['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
。我想删除所有单词:and
,or
,of
。一、 因此,提出以下代码块
my_list = ['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
print('Before: {}'.format(my_list))
my_list = list(filter(lambda a: 'and' not in a and 'of' not in a and 'or' not in a, my_list))
print('After: {}'.format(my_list))
但是,我的代码给出如下输出
Before: ['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
After: []
我想要的应该是
['land_transport', 'port', 'surveyor', 'organization']
当然,有几种方法。但是我想坚持使用lambda函数来解决这个问题。对我的问题有什么建议吗?你知道吗
虽然以上的答案符合需要,但我认为你打算删除停止语。你知道吗
nltk
是Python中最好的资源。你可以使用nltk.corpus.stopwords你不必做太多的操作,如果你知道你正在删除实际的英语停止词。你知道吗
沃拉
您的筛选不正确,请使用:
如果需要
my_list
中所有不在filter_set
中的项,请注意使用set
,它将使查找更快(O(N) vs O(1))
。你知道吗您可以创建一个新列表,存储要筛选的所有单词:
输出:
相关问题 更多 >
编程相关推荐