Python discard()

python 中的discard()函数有助于在元素存在的情况下从集合中移除或丢弃指定的元素。

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

丢弃()参数:

discard()函数接受一个参数。此方法类似于remove()方法,不同之处在于,如果给定元素不在集合中,discard()方法会引发错误,但remove()不会。

参数 描述 必需/可选
元素 要搜索和移除的项目 需要

丢弃()返回值

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

Python 中discard()方法的示例

示例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'} 

示例 Python 中丢弃()的工作方式

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

输出:

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

你可能感兴趣的