當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Set remove()用法及代碼示例

設置 remove() 方法

remove() 方法用於從集合中移除指定元素,該方法接受一個元素,如果存在則從集合中移除,如果該元素在集合中不存在,則該方法返回錯誤。

用法:

    set_name.remove(element)

參數:

  • element– 它表示要從列表中刪除的元素。

返回值:

這個方法的返回類型是<class 'NoneType'>,它什麽都不返回。

範例1:

# Python Set remove() Method with Example

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
nums = {100, 200, 300, 400, 500}

# printing the sets before removing
print("Before the calling remove() method...")
print("cars:", cars)
print("nums:", nums)

# Removing the elements from the sets
cars.remove("Porsche")
cars.remove("Mazda")

nums.remove(100)
nums.remove(500)

# printing the sets after removing
print("After the calling remove() method...")
print("cars:", cars)
print("nums:", nums)

輸出

Before the calling remove() method...
cars: {'Mazda', 'Audi', 'Porsche', 'Lexus', 'Lincoln'}
nums: {100, 200, 300, 400, 500}
After the calling remove() method...
cars: {'Audi', 'Lexus', 'Lincoln'}
nums: {200, 300, 400}

演示示例,如果在集合中找不到元素,方法如何引發錯誤?

範例2:

# Python Set remove() Method with Example

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}

# printing the set
print("cars:", cars)
# removing an item (which exists in the set)
cars.remove("Porsche")
# printing the set again
print("cars:", cars)

# removing an item (which does not exist in the set)
# it will return an error
cars.remove("BMW")

輸出

cars: {'Mazda', 'Audi', 'Lexus', 'Porsche', 'Lincoln'}
cars: {'Mazda', 'Audi', 'Lexus', 'Lincoln'}
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    cars.remove("BMW")
KeyError:'BMW'


相關用法


注:本文由純淨天空篩選整理自 Python Set remove() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。