如何按值从Python列表中删除项目? [英] How do I remove an item from a Python list by value?
本文介绍了如何按值从Python列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想按项目的值而不是其索引删除项目,我该怎么办?
If I wanted to remove an item by its value instead of its index what would I do?
animals = ['tiger', 'snake', 'penguin','giraffe']
说我想删除'penguin'
而不键入del animals[2]
怎么办?
Say I wanted to remove 'penguin'
without typing del animals[2]
how would I go about it?
我尝试输入del animals['penguin']
,但是它不起作用...
I've tried typing del animals['penguin']
but it doesn't work...
推荐答案
animals.remove("penguin")
对吗?授予它只会删除第一个值,但是它将按值删除它,而不是索引.并且不需要构建新列表或需要额外的调用来查找给定值的索引.
Right? Granted it only removes the first value, but it will remove it by value not index. And will not require building a new list or require an extra call to lookup the index of the given value.
这篇关于如何按值从Python列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文