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


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

設置 discard() 方法

discard() 方法用於從集合中刪除給定元素,它接受一個元素並將其從集合中刪除。

注意:如果給定的元素在集合中不存在,則“discard() 方法”不會返回任何錯誤。

用法:

    set_name.discard(element)

參數:

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

返回值:

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

範例1:

# Python Set discard() Method with Example

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

# printing the sets before discard() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)

# removing an element from cars_1
cars_1.discard("Porsche")
# removing an element from cars_2
cars_2.discard("Lincoln")

# printing the sets after dLincoln() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)

輸出

cars_1:{'Audi', 'Lexus', 'Porsche'}
cars_2:{'Mazda', 'Porsche', 'Lincoln'}
cars_1:{'Audi', 'Lexus'}
cars_2:{'Mazda', 'Porsche'}

範例2:

# Python Set discard() Method with Example

# declaring a set
cities = {"New Delhi", "Banglore", "Indore", "Gwalior"}

# printing set before discard() call
print("cities:", cities)

# removing "New Delhi" from the set
cities.discard("New Delhi")

# removing an element that does not exist
# in the set, thus we will remove "Mumbai"
# method discard() will not give any error
cities.discard("Mumbai")

# printing set after discard() call
print("cities:", cities)

輸出

cities:{'New Delhi', 'Gwalior', 'Indore', 'Banglore'}
cities:{'Gwalior', 'Indore', 'Banglore'}


相關用法


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