如何根据另一个列表的内容删除一个列表中的列表元素?

时间:2019-06-09 15:01:30

标签: python dataset list-comprehension

我在python中的列表理解有问题。我在搜索查询中有一个字符串变量,如下所示:

queries = 'news, online movies, weather, golden rush, online sports, price 
of the golden ring, today weather, python'

我列出了2个元素:

words = [ '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']

1 个答案:

答案 0 :(得分:1)

尝试一下。

    queries = 'news, online movies, weather, golden rush, online sports, price of the golden ring, today weather, python'
    queries = queries.split(',')
    words = [ 'online', 'golden' ]
    print([x for x in queries if not any(word in x for word in words)])
    # ['news', ' weather', ' today weather', ' python']

python any()文档请参见https://docs.python.org/3/library/functions.html#any