Tutorial Study Image

Python discard()

Python 中的 discard() 函数有助于从集合中删除或丢弃指定元素,前提是该元素存在。


s.discard(element) #where element may be a integer,string etc.
 

discard() 参数

discard() 函数接受一个参数。此方法与 remove() 方法类似,区别在于如果给定元素不存在于集合中,remove() 方法会引发错误,而 discard() 则不会。

参数 描述 必需/可选
元素 要搜索并删除的项 必需

discard() 返回值

discard() 方法不返回任何内容。它只是通过从集合中删除指定元素来更新集合。

Python 中 discard() 方法的示例

示例 1:discard() 在 Python 中如何工作?


alphabets = {'a', 'b', 'c', 'd'}

alphabets .discard(c)
print('Alphabets = ', alphabets )

numbers.discard(e)
print('Alphabets = ', alphabets )
 

输出


Alphabets =  {'a', 'b', 'd'}
Alphabets =  {'a', 'b', 'd'}

示例 2:Python 中 discard() 的工作原理


alphabets = {'a', 'b', 'c', 'd'}
#Returns none
print(alphabets .discard(c))
print('Alphabets = ', alphabets )
 

输出


None
Alphabets = {'a', 'b', 'd'}