loops - 从 Python 3.x 中的另一个列表中删除单独的项目列表

标签 loops python-3.x list-comprehension remove-if

我有一个包含很多标记二元组的列表。有些二元组没有正确标记,所以我想将它们从主列表中删除。二元组中的一个单词经常重复,因此如果它包含 xyz 单词,我可以删除该二元组。伪示例如下:

master_list = ['this is', 'is a', 'a sample', 'sample word', 'sample text', 'this book', 'a car', 'literary text', 'new book', 'them about', 'on the' , 'in that', 'tagged corpus', 'on top', 'a car', 'an orange', 'the book', 'them what', 'then how']

unwanted_words = ['this', 'is', 'a', 'on', 'in', 'an', 'the', 'them']

new_list = [item for item in master_list if not [x for x in unwanted_words] in item]

我可以单独删除这些项目,即每次创建列表并删除包含“on”一词的项目时。这很乏味,并且需要数小时的过滤和创建新列表来过滤每个不需要的单词。我认为循环会有帮助。但是,我收到以下类型错误:

Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
new_list = [item for item in master_list if not [x for x in  unwanted_words] in item]
File "<pyshell#21>", line 1, in <listcomp>
new_list = [item for item in master_list if not [x for x in unwanted_words] in item]
TypeError: 'in <string>' requires string as left operand, not list

非常感谢您的帮助!

最佳答案

您的条件 if not [x for x in irreversible_words] in itemif not irreversible_words in item 相同,即您正在检查列表是否 包含在字符串中。

相反,您可以使用 any检查二元组的任何部分是否在 unwanted_words 中。另外,您可以将 unwanted_words 设置为 set 以加快查找速度。

>>> master_list = ['this is', 'is a', 'a sample', 'sample word', 'sample text', 'this book', 'a car', 'literary text', 'new book', 'them about', 'on the' , 'in that', 'tagged corpus', 'on top', 'a car', 'an orange', 'the book', 'them what', 'then how']
>>> unwanted_words = set(['this', 'is', 'a', 'on', 'in', 'an', 'the', 'them'])
>>> [item for item in master_list if not any(x in unwanted_words for x in item.split())]
['sample word', 'sample text', 'literary text', 'new book', 'tagged corpus', 'then how']

关于loops - 从 Python 3.x 中的另一个列表中删除单独的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29188896/

相关文章:

c# - 如何测试是否检查了 TreeView 节点和/或节点子节点?

c++ - 在C++类中执行while循环

python - 根据另一个键过滤字典列表以删除键中的重复项

python - 如何通过 .extend 列表方法使用列表理解?

python - 嵌套列表理解

python - 将排序列表重新映射到字典中

python - 将不同列表中的选定项目组合成一个新项目

javascript - *日历程序* 无法为该日历程序编写循环以正确显示

python - 交换从树移动指针中随机选择的两个节点的角色的算法

python - 组合字符串列表,提高性能