溫馨提示×

python怎么刪除列表指定元素

小億
84
2023-12-14 20:00:20
欄目: 編程語言

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

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

如果要刪除列表中所有的指定元素,可以使用循環(huán)來遍歷列表并刪除匹配的元素。例如,刪除列表中所有的元素"apple":

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

另一種方法是使用列表推導(dǎo)式來創(chuàng)建一個新的列表,其中不包含指定的元素。例如,刪除列表中的元素"apple":

fruits = ["apple", "banana", "cherry"]
fruits = [fruit for fruit in fruits if fruit != "apple"]
print(fruits)  # 輸出:["banana", "cherry"]

0