共計 388 個字符,預計需要花費 1 分鐘才能閱讀完成。
在 Python 中,可以使用 remove()
方法或 discard()
方法刪除集合中的元素。
使用 remove()
方法時,如果要刪除的元素不存在于集合中,將會引發(fā) KeyError
錯誤。例如:
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # 輸出: {1, 2, 4, 5}
my_set.remove(6) # 引發(fā) KeyError 錯誤,因為 6 不在集合中
使用 discard()
方法時,在元素不存在于集合中的情況下,不會引發(fā)任何錯誤。例如:
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set) # 輸出: {1, 2, 4, 5}
my_set.discard(6) # 不會引發(fā)錯誤,因為 6 不在集合中
需要注意的是,使用這兩個方法刪除元素時,如果元素不存在于集合中,刪除操作不會產(chǎn)生任何影響。
丸趣 TV 網(wǎng) – 提供最優(yōu)質的資源集合!
正文完