如何从列表中删除包含在另一个列表中的项目中找到的单词的项目 [英] How to remove items from a list that contains words found in items in another list

查看:68
本文介绍了如何从列表中删除包含在另一个列表中的项目中找到的单词的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从列表"a"中删除项目,其中列表"b"包含在列表"a"中找到带有单词的项目

I want to remove items from list 'a' where list 'b' contains items with words found in list 'a'

a = ['one two three', 'four five six', 'seven eight nine']
b = ['two', 'five six']

结果应为:

a = ['seven eight nine']

这是因为在列表"a"的项目中找到了二"和五六".

This because the words 'two' and 'five six' are found in items in list 'a'.

这是我尝试解决的方法:

This is how I have tried to solve it:

for i in a:
    for x in b:
        if x in i:
            a.remove(i)

这将返回:

print a
['four five six', 'seven eight nine']

为什么这不起作用,我该如何解决这个问题?

Why does this not work, and how can I solve this problem?

谢谢.

推荐答案

在迭代列表时,不应修改列表.这样做会产生不良的副作用,例如循环跳过项目.

Lists should not be modified while they're being iterated over. Doing so can have undesirable side effects, such as the loop skipping over items.

通常在Python中,您应该避免循环一次在列表中添加和删除元素的循环.通常,这些循环可以用更多惯用的列表理解代替.

Generally in Python you should avoid loops that add and remove elements from lists one at a time. Usually those kinds of loops can be replaced with more idiomatic list comprehensions.

[sa for sa in a if not any(sb in sa for sb in b)]

就其价值而言,按书面方式修复循环的一种方法是遍历列表的副本,以使循环不受原始更改的影响.

For what it's worth, one way to fix your loops as written would be to iterate over a copy of the list so the loop isn't affected by the changes to the original.

for i in a[:]:
    for x in b:
        if x in i:
            a.remove(i)

这篇关于如何从列表中删除包含在另一个列表中的项目中找到的单词的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆