【发布时间】:2019-10-24 05:19:10
【问题描述】:
我在 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']
【问题讨论】:
-
为什么要标记熊猫?这是熊猫系列吗??
-
对不起我用错了
-
print( [ x for x in queries if x not in words ]很接近。除了缺少结束括号之外,您还忽略了查询只是一个字符串这一事实,并且需要您在其他方法中完成的逗号分割。 -
为什么您在第一次尝试的解决方案中有
break?这将完全停止循环,而不处理剩余的元素。此外,在您尝试的第二个解决方案中,queries是一个字符串,而不是一个列表,因此循环它会给您单个字符。 -
归结为:
filtered_query = [item for item in queries.split(",") if not any(w in item for w in words) ]
标签: python dataset list-comprehension