在Python中删除列表中的元素的完整指南

172 阅读2分钟

虽然如果你要从中间进行大量的删除,列表并不是最有效的数据结构,但绝对有好的方法来完成这个任务。内置的 [remove()](https://python-reference.readthedocs.io/en/latest/docs/list/remove.html)方法应该是你的第一选择,我们来看看一些例子。

在Python列表中按值删除元素

primes = [2, 3, 5, 5, 7, 11]

primes.remove(5)

print(primes)
# [2, 3, 5, 7, 11]

primes.remove(5)
# [2, 3, 7, 11]

primes.remove(5)
# careful, this will throw an error
# ValueError: list.remove(x): x not in list

Code language: Python (python)

如果你想安全地删除项目,而你又不确定它们是否存在于列表中,你可以捕捉错误。

try:
	primes.remove(5)
except Exception as e:
	print("not in list")

或者,你可以先检查是否存在:

if 5 in primes:
	primes.remove(5)

按索引删除Python列表中的一个元素

del 语句是一个内置的关键字,允许你从列表中删除项目。最简单的例子是删除指定索引处的项目。

primes = [2, 3, 5, 5, 7, 11]

# delete the second item
del primes[1]

print(primes)
# [2, 5, 5, 7, 11]

同样,你需要小心。如果索引不存在,就会产生错误:

primes = [2, 3, 5, 5, 7, 11]

# delete the eleventh item
del primes[10]

IndexError: list assignment index out of range

if len(primes) >= 10:
	del primes[10]

从 python 列表中删除多个项目

primes = [2, 3, 5, 5, 7, 11]

# deleting items from 2nd to 4th
del primes[1:4]

print(primes)
# [2, 7, 11]

按索引删除项目并返回

.pop() 方法从一个列表中按索引删除一个项目并返回该项目。

primes = [2, 3, 5, 7]

# pop the second element
popped = primes.pop(1)

print("popped:", popped)
# 3

print("list:", primes)
# [2, 5, 7]

如果你没有给pop() 传递一个索引参数,它将默认为-1 并从列表中删除最后一个元素。就像其他方法一样,如果你传入的数字太大,你会得到以下错误:

IndexError: pop index out of range