温馨提示×

python中的set如何删除元素

小樊
85
2024-11-21 20:21:37
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用remove()方法来删除集合(set)中的指定元素。该方法接受一个参数,即要删除的元素的值。如果元素不存在于集合中,则会引发一个KeyError异常。

以下是一个示例:

my_set = {1, 2, 3, 4, 5}
print("Original set:", my_set)

# 删除元素3
my_set.remove(3)
print("Set after removing 3:", my_set)

# 尝试删除不存在的元素7
try:
    my_set.remove(7)
except KeyError:
    print("Element 7 not found in the set.")

输出:

Original set: {1, 2, 3, 4, 5}
Set after removing 3: {1, 2, 4, 5}
Element 7 not found in the set.

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python中set怎样删除元素

0