只需一个语句即可从Python列表中删除多个项目

时间:2016-03-28 18:38:13

标签: python

在python中,我知道如何从列表中删除项目。

item_list = ['item', 5, 'foo', 3.14, True]
item_list.remove('item')
item_list.remove(5)

以上代码从item_list中删除了值5和'item'。 但是当有很多东西需要删除时,我必须编写很多行

item_list.remove("something_to_remove")

如果我知道要删除的内容的索引,我会使用:

del item_list[x]

其中x是我要删除的项目的索引。

如果我知道要删除的所有数字的索引,我将使用某种循环来del索引处的项目。

但如果我不知道我要删除的项目的索引怎么办?

我尝试了item_list.remove('item', 'foo'),但我收到一条错误消息,指出remove只接受一个参数。

有没有办法在单个语句中从列表中删除多个项目?

P.S。我使用过delremove。有人可以解释这两者之间的区别,还是一样?

由于

7 个答案:

答案 0 :(得分:81)

在Python中,创建新对象通常比修改现有对象更好:

item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]

相当于:

item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
    if e not in ('item', 5):
        new_list.append(e)
item_list = new_list

如果有大量滤出值(此处('item', 5)是一小组元素),使用set可以提高性能,因为in操作在O(1):

item_list = [e for e in item_list if e not in {'item', 5}]

请注意,正如评论和建议here中所述,以下内容可以节省更多时间,避免在每个循环中构建集:

unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]

如果内存不便宜,bloom filter也是一个很好的解决方案。

答案 1 :(得分:17)

item_list = ['item', 5, 'foo', 3.14, True]
list_to_remove=['item', 5, 'foo']
删除后的最终列表应如下

final_list=[3.14, True]

单行代码

final_list= list(set(item_list).difference(set(list_to_remove)))

输出如下

final_list=[3.14, True]

答案 2 :(得分:1)

  

但如果我不知道我要删除的项目的索引怎么办?

我不完全理解为什么你不喜欢.remove但要获得对应于值的第一个索引使用.index(value):

ind=item_list.index('item')

然后.pop删除相应的值:

item_list.pop(ind)

.index(value)获取第一次出现的值,而.remove(value)删除第一次出现的值

答案 3 :(得分:1)

我将here的答案重新发布,因为我看到它也符合这里的要求。 它允许删除多个值或仅删除这些值的重复项 并返回一个新列表或修改给定列表。

def removed(items, original_list, only_duplicates=False, inplace=False):
    """By default removes given items from original_list and returns
    a new list. Optionally only removes duplicates of `items` or modifies
    given list in place.
    """
    if not hasattr(items, '__iter__') or isinstance(items, str):
        items = [items]

    if only_duplicates:
        result = []
        for item in original_list:
            if item not in items or item not in result:
                result.append(item)
    else:
        result = [item for item in original_list if item not in items]

    if inplace:
        original_list[:] = result
    else:
        return result

Docstring扩展名:

"""
Examples:
---------

    >>>li1 = [1, 2, 3, 4, 4, 5, 5]
    >>>removed(4, li1)
       [1, 2, 3, 5, 5]
    >>>removed((4,5), li1)
       [1, 2, 3]
    >>>removed((4,5), li1, only_duplicates=True)
       [1, 2, 3, 4, 5]

    # remove all duplicates by passing original_list also to `items`.:
    >>>removed(li1, li1, only_duplicates=True)
      [1, 2, 3, 4, 5]

    # inplace:
    >>>removed((4,5), li1, only_duplicates=True, inplace=True)
    >>>li1
        [1, 2, 3, 4, 5]

    >>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
    >>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
    >>>li2
        ['abc', 'def', 'ghi']
"""

您应该清楚自己真正想做什么,修改现有列表或制作新列表 缺少的具体项目。如果您有第二个引用指向,那么区分它是很重要的 到现有的清单。如果你有,例如......

li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
# then rebind li1 to the new list without the value 4
li1 = removed(4, li1)
# you end up with two separate lists where li2 is still pointing to the 
# original
li2
# [1, 2, 3, 4, 4, 5, 5]
li1
# [1, 2, 3, 5, 5]

这可能是您想要的行为,也可能不是。

答案 4 :(得分:1)

您可以从filterfalse模块使用itertools功能

示例

import random
from itertools import filterfalse

random.seed(42)

data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")


clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")

输出:

Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]

Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]

答案 5 :(得分:0)

我不知道为什么每个人都忘记提及set在python中的惊人功能。您可以简单地将列表转换为集合,然后使用以下简单表达式删除要删除的所有内容:

>>> item_list = ['item', 5, 'foo', 3.14, True]
>>> item_list = set(item_list) - {'item', 5}
>>> item_list
{True, 3.14, 'foo'}
>>> # you can cast it again in a list-from like so
>>> item_list = list(item_list)
>>> item_list
[True, 3.14, 'foo']

答案 6 :(得分:-2)

您可以使用此-

假设我们有一个列表,l = [1,2,3,4,5]

我们要在一个语句中删除最后两个项目

del l[3:]

我们有输出:

l = [1,2,3]

保持简单