Python 从集合中移除元素
从集合中移除元素
要从集合中移除一个元素,可以使用 remove() 或 discard() 方法。
例子 1
使用 remove() 方法移除 "banana":
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
注意:如果要移除的元素不存在,remove() 会引发错误。
例子 2
使用 discard() 方法移除 "banana":
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
注意:如果要移除的元素不存在,discard() 不会引发错误。
您还可以使用 pop() 方法来移除一个元素,但此方法将移除最后一个元素。请记住,集合是无序的,因此您不会知道哪个元素将被移除。
pop() 方法的返回值是被移除的元素。
例子 3
使用 pop() 方法移除最后一个元素:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
注意:集合是无序的,因此当使用 pop() 方法时,您不会知道哪个元素将被移除。
例子 4
clear() 方法将清空集合:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
例子 5
del 关键字将完全删除集合:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)