discard()
方法从 集合 中删除指定的项。
示例
numbers = {2, 3, 4, 5}
# removes 3 and returns the remaining set
numbers.discard(3)
print(numbers)
# Output: numbers = {2, 4, 5}
discard() 语法
discard()
方法的语法是
a.discard(x)
这里,a 是集合,x 是要丢弃的项。
discard() 参数
discard()
方法接受一个参数
- x - 要从集合中移除的项
discard() 返回值
discard()
方法不返回任何值。
示例 1:Python Set discard()
numbers = {2, 3, 4, 5}
# discards 3 from the set
numbers.discard(3)
print('Set after discard:', numbers)
输出
Set after discard: {2, 4, 5}
在上面的示例中,我们使用了 discard()
从集合中删除一项。由于 discard()
方法已将其删除,结果集合中不包含项 3。
示例 2:Python Set discard() 处理不存在的项
numbers = {2, 3, 5, 4}
print('Set before discard:', numbers)
# discard the item that doesn't exist in set
numbers.discard(10)
print('Set after discard:', numbers)
输出
Set before discard: {2, 3, 4, 5} Set after discard: {2, 3, 4, 5}
在上面的示例中,我们使用了 discard()
方法丢弃集合中不存在的项。在这种情况下,原始集合 numbers 即 {2, 3, 5, 4}
保持不变,我们不会收到任何错误。
另请阅读