当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。