Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

python - 如何通过索引从列表中删除元素?(How to remove an element from a list by index?)

How do I remove an element from a list by index in Python?

(如何在Python中按索引从列表中删除元素?)

I found the list.remove method, but say I want to remove the last element, how do I do this?

(我找到了list.remove方法,但是说我想删除最后一个元素,该怎么做?)

It seems like the default remove searches the list, but I don't want any search to be performed.

(似乎默认的remove搜索列表,但是我不希望执行任何搜索。)

  ask by Joan Venge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use del and specify the index of the element you want to delete:

(使用del并指定要删除的元素的索引:)

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Also supports slices:

(还支持切片:)

>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]

Here is the section from the tutorial.

(是教程中的部分。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...