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


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

Python discard() 方法從集合中丟棄或刪除元素。此方法不返回任何內容,如果元素不存在,則甚至不會返回任何錯誤。它需要一個參數,該參數是要刪除的元素。方法簽名如下。

簽名

discard(elem)

參數

elem: 要刪除的元素。

返回

它返回無。

讓我們看一些 discard() 方法的例子來了解它的函數。

Python 設置 discard() 方法示例 1

使用丟棄方法刪除元素的簡單示例。

# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set) 
# Calling function
set.discard(2)
print(set)

輸出:

{1, 2, 3, 4, 5}
{1, 3, 4, 5}

Python 設置 discard() 方法示例 2

如果該元素不存在,則它不向調用者方法返回 none。

# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set) 
# Calling function
val = set.discard(22)
print(val)

輸出:

{1, 2, 3, 4, 5}
None

Python 設置 discard() 方法示例 3

我們在程序中實現此方法的示例。它刪除了所有賠率元素。

# Python set discard() Method
# Creating a set
set = {1,2,3,4,5}
set2 = {1,2,3,4,5}
# Displaying elements
print(set) 
# Calling function
for s in set2:
    if s%2!=0:
        set.discard(s)  # Discard all odd elements
print(set)

輸出:

{1, 2, 3, 4, 5}
{2, 4}






相關用法


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