在Python中,discard是set對象的一個方法,用于刪除集合中的指定元素。如果集合中存在要刪除的元素,則該元素會被刪除;如果集合中不存在要刪除的元素,則該方法不會引發錯誤,而是靜默地完成操作。示例如下:
discard
set
s = {1, 2, 3, 4} s.discard(2) print(s) # Output: {1, 3, 4} s.discard(5) print(s) # Output: {1, 3, 4}