只需一条语句即可从 Python 列表中删除多项 [英] Remove multiple items from a Python list in just one statement

查看:41
本文介绍了只需一条语句即可从 Python 列表中删除多项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In python, I know how to remove items from a list.

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

以上代码从 item_list 中删除了值 5 和 'item'.但是当有很多东西要删除时,我不得不写很多行

This above code removes the values 5 and 'item' from item_list. But when there is a lot of stuff to remove, I have to write many lines of

item_list.remove("something_to_remove")

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

If I know the index of what I am removing, I use:

del item_list[x]

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

where x is the index of the item I want to remove.

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

If I know the index of all of the numbers that I want to remove, I'll use some sort of loop to del the items at the indices.

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

But what if I don't know the indices of the items I want to remove?

我尝试了 item_list.remove('item', 'foo'),但是我收到一个错误,说 remove 只接受一个参数.

I tried item_list.remove('item', 'foo'), but I got an error saying that remove only takes one argument.

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

Is there a way to remove multiple items from a list in a single statement?

附言我使用过 delremove.有人能解释一下这两者之间的区别吗,或者它们是一样的?

P.S. I've used del and remove. Can someone explain the difference between these two, or are they the same?

谢谢

推荐答案

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

In Python, creating a new object is often better than modifying an existing one:

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) 是一小组元素),使用 setin 操作 平均时间复杂度为 O(1).首先构建您要删除的迭代也是一个好主意,这样您就不会在列表理解的每次迭代中都创建它:

In case of a big list of filtered out values (here, ('item', 5) is a small set of elements), using a set is faster as the in operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:

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

如果内存不便宜,布隆过滤器也是一个不错的解决方案.

A bloom filter is also a good solution if memory is not cheap.

这篇关于只需一条语句即可从 Python 列表中删除多项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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