我对python中的列表理解有问题。我有一个带有搜索查询的字符串变量,如下所示:
queries = 'news, online movies, weather, golden rush, online sports, price
of the golden ring, today weather, python'
我有两个元素的列表:
words = [ 'online', 'golden' ]
我需要用列表词过滤查询字符串,这样最终的结果就不会包括内容中有“online”和“golden”的查询。你知道吗
我试过了,但效果不太好:
filteredquerry = []
queriesNew = queries.split(',')
for x in queriesNew:
if x not in words:
filteredquerry.append(x)
else:
break
print(filteredquerry)
此外,我还尝试了另一种使用列表方法的列表“过滤”方法,但它会给我一个错误或返回一个空列表:
print( [ x for x in queries if x not in words ]
预期结果如下所示:
filteredquerry = ['news', 'weather', 'today weather', 'python']
试试这个。你知道吗
python any()文档请参见https://docs.python.org/3/library/functions.html#any
相关问题 更多 >
编程相关推荐