📜  Python Set – remove() 方法

📅  最后修改于: 2022-05-13 01:55:43.412000             🧑  作者: Mango

Python Set – remove() 方法

Python remove()函数是从集合中移除元素的内置方法。 remove() 方法只接受一个参数。

句法

set.remove(element)

如果传递给 remove() 的元素存在于集合中,则该元素将从集合中移除。如果传递给 remove() 的元素在集合中不存在,则会引发 KeyError 异常。 remove() 方法不返回任何值。

示例 1:

Python3
numbers = {1,2,3,4,5,6,7,8,9}
print(numbers)
  
# Deleting 5 from the set
numbers.remove(5)
  
# printing the resultant set
print(numbers)


Python3
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  
print(numbers)
  
# passing an element that is not in set
# this will throw an KeyError exception
try:
    numbers.remove(13)
except Exception as e:
    print("KeyError Exception raised")
    print(e, "is not present in the set")
  
# printing the resultant set
print("\nresultant set : ", numbers)


输出
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 6, 7, 8, 9}

示例 2:

Python3

numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  
print(numbers)
  
# passing an element that is not in set
# this will throw an KeyError exception
try:
    numbers.remove(13)
except Exception as e:
    print("KeyError Exception raised")
    print(e, "is not present in the set")
  
# printing the resultant set
print("\nresultant set : ", numbers)
输出
{1, 2, 3, 4, 5, 6, 7, 8, 9}
KeyError Exception raised
13 is not present in the set

resultant set :  {1, 2, 3, 4, 5, 6, 7, 8, 9}