Linux 拨号vps windows公众号手机端

python怎么删除列表指定元素

lewis 8年前 (2017-07-19) 阅读数 11 #程序编程
文章标签 python

可以使用remove()方法删除列表中的指定元素。例如,删除列表中的元素"apple":

fruits = ["apple", "banana", "cherry"]
fruits.remove("apple")
print(fruits)  # 输出:["banana", "cherry"]

如果要删除列表中所有的指定元素,可以使用循环来遍历列表并删除匹配的元素。例如,删除列表中所有的元素"apple":

fruits = ["apple", "banana", "cherry", "apple"]
while "apple" in fruits:
    fruits.remove("apple")
print(fruits)  # 输出:["banana", "cherry"]

另一种方法是使用列表推导式来创建一个新的列表,其中不包含指定的元素。例如,删除列表中的元素"apple":

fruits = ["apple", "banana", "cherry"]
fruits = [fruit for fruit in fruits if fruit != "apple"]
print(fruits)  # 输出:["banana", "cherry"]
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门