Python Set discard() 方法用于从集合中删除指定的元素。与 remove() 方法不同,如果在集合中找不到该元素,则不会引发错误,并且集合保持不变。当您不确定该元素是否存在于集合中时,此方法是比 remove() 方法更安全的替代方法。
语法
以下是 Python Set discard() 方法的语法和参数 -
set.discard(element)
参数
以下是 discard() 方法的参数 -
- element:要从集合中删除的元素(如果存在)。
返回值
此方法返回包含所有指定集共有的元素的新集。
示例 1
以下是 python set discard() 方法的基本示例。在这个例子中,我们正在创建一个具有指定元素的集合,并使用 discard() 方法从集合中删除元素 3 -
# 定义一个集合
my_set = {1, 2, 3, 4, 5}
# 从组件中移除元件3
my_set.discard(3)
print(my_set)
输出
{1, 2, 4, 5}
示例 2
当我们尝试删除不在集合中的元素时,不会引发错误。以下示例显示,由于指定的元素 6 在集合中不存在,因此不会引发错误 -
# 定义一个集合
my_set = {1, 2, 4, 5}
# 尝试从集合中删除不存在的元素6
my_set.discard(6)
print(my_set)
输出
{1, 2, 4, 5}
示例 3
在此示例中,discard() 方法与条件语句一起使用,以安全地从集合中删除元素 -
# 定义一个集合
my_set = {1, 2, 3, 4, 5}
# 如果存在,请安全地移除元件
if 3 in my_set:
my_set.discard(3)
print(my_set)
输出
{1, 2, 4, 5}
示例 4
discard() 和 remove() 方法之间的主要区别在于,如果未找到元素,discard() 不会引发错误,而 remove() 会引发 KeyError。在这个例子中,我们展示了 remove() 方法和 discard() 方法之间的区别 -
# 定义一个集合
my_set = {1, 2, 4, 5}
# 尝试使用discard()删除不存在的元素3
my_set.discard(3)
print(my_set) # Output: {1, 2, 4, 5}
# 尝试使用remove()删除不存在的元素3
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
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