从列表中删除选定元素

7 浏览
0 Comments

从列表中删除选定元素

此问题已经有了答案:

如何在一条语句中从列表中删除多个项?

我目前正在使用列表这个数据结构,并想知道如何从一个列表中删除另一个列表中出现的所有元素。我曾在Stack Overflow上看到过几个例子,其中讨论了如何从列表中删除单个元素,但是没有涉及到删除多个相同元素的情况(例如下面的例子,不手动删除每个实例)。例如,给定以下两个列表:

friends_pets = ['Chicken', 'Chicken' 'Dog', 'Pigeon', 'Dog', 'Cat', 'Cat', 'Cat']
personal_pets = ['Dog', 'Cat']

我希望我的函数返回:

>>> ['Chicken', 'Chicken', 'Pigeon']

我认为使用filter()方法返回所需列表而不是remove() 看起来最理想,但是,我无法访问Python在特定地址上存储的信息。

for pet in personal_pets:
    filter(pet, friends_pets)
>>> 
>>> 

我甚至尝试了运行:

for pet in personal_pets:
    list(filter(pet, friends_pets))

然而,它表明\'str\'对象不可调用。

我使用remove()能够获得最接近的结果:

for pet in personal_pets:
    friends_pets.remove(pet)
>>> ['Chicken', 'Chicken', 'Pigeon', 'Dog', 'Cat', 'Cat', 'Cat']

admin 更改状态以发布 2023年5月21日
0
0 Comments

使用 set 来保持运行时间在 O(n) 级别。

有多种方法可以做到这一点。

如果输入可能很大,则使用生成器:

def exclude_items(original_list, items_to_exclude):
    # Create a set as lookup time is O(1).
    # It can be O(log N) in case of collisions though still better than O(n) without it
    to_exclude = set(items_to_exclude)
    for item in original_list:
        if item not in to_exclude:
           yield item

不使用生成器:

def exclude_items(original_list, items_to_exclude):
    to_exclude = set(items_to_exclude)
    return [item for item in original_list if item not in to_exclude]

0
0 Comments

使用filter时,使用的函数是过滤掉不想要的宠物的lambda表达式。在这里,使用了列表new,这样可以不破坏friends_pets列表。否则,你可以使用那个数组而不是new

然而,这种方法是浪费的,因为它为每个个人宠物重建了新的数组。

>>> new = []
>>> new = [] + friends_pets
>>> for pet in personal_pets:
    new = list(filter(lambda x: x != pet, new))
>>> new
['Chicken', 'Chicken', 'Pigeon']

可以使用列表推导更简单地完成。

>>> L = [pet for pet in friends_pets if pet not in set(personal_pets)]
>>> L
['Chicken', 'Chicken', 'Pigeon']

在这里使用集合可以加速,如果列表很大的话。

更新:必须在friends_pets中添加缺失的逗号

friends_pets = ['Chicken', 'Chicken', 'Dog', 'Pigeon', 'Dog', 'Cat', 'Cat', 'Cat']

第二只鸡和狗之间缺少逗号。奇怪的是,它把它们当作单个字符串处理,我不理解为什么。

0