Python 集合 discard() 方法



Python 集合 discard() 方法用於從集合中刪除指定的元素。與 remove() 方法不同,如果集合中不存在該元素,則不會引發錯誤,集合保持不變。當您不確定元素是否存在於集合中時,此方法是 remove() 方法的更安全替代方案。

語法

以下是 Python 集合 discard() 方法的語法和引數:

set.discard(element)

引數

以下是 discard() 方法的引數:

  • element: 要從集合中刪除的元素(如果存在)。

返回值

此方法返回一個新集合,其中包含所有指定集合的公共元素。

示例 1

以下是 python 集合 discard() 方法的基本示例。在此示例中,我們使用指定元素建立一個集合,並使用 discard() 方法從集合中刪除元素 3:

# Define a set
my_set = {1, 2, 3, 4, 5}

# Remove element 3 from the set
my_set.discard(3)

print(my_set)  

輸出

{1, 2, 4, 5}

示例 2

當我們嘗試刪除集合中不存在的元素時,不會引發錯誤。以下示例顯示了這一點,因為指定的元素 6 不存在於集合中,所以沒有引發錯誤:

# Define a set
my_set = {1, 2, 4, 5}

# Try to remove non-existing element 6 from the set
my_set.discard(6)

print(my_set) 

輸出

{1, 2, 4, 5}

示例 3

在此示例中,discard() 方法與條件語句一起使用,以安全地從集合中刪除元素:

# Define a set
my_set = {1, 2, 3, 4, 5}

# Safely remove element if present
if 3 in my_set:
    my_set.discard(3)

print(my_set) 

輸出

{1, 2, 4, 5}

示例 4

discard() 和 remove() 方法之間的關鍵區別在於,如果找不到該元素,discard() 不會引發錯誤,而 remove() 會引發 KeyError。在此示例中,我們展示了 remove() 方法和 discard() 方法之間的區別:

# Define a set
my_set = {1, 2, 4, 5}

# Try to remove non-existing element 3 using discard()
my_set.discard(3)

print(my_set)  # Output: {1, 2, 4, 5}

# Try to remove non-existing element 3 using remove()
my_set.remove(3)  # This raises a KeyError since 3 is not present in the set

輸出

{1, 2, 4, 5}
Traceback (most recent call last):
  File "\sample.py", line 10, in <module>
    my_set.remove(3)  # This raises a KeyError since 3 is not present in the set
    ^^^^^^^^^^^^^^^^
KeyError: 3
python_set_methods.htm
廣告