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

2024-09-30 02:19:26 发布

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

我对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']

Tags: 字符串in列表fortodayifnotonline
1条回答
网友
1楼 · 发布于 2024-09-30 02:19:26

试试这个。你知道吗

    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

相关问题 更多 >

    热门问题