Python 集合 discard() 方法
示例
numbers = {2, 3, 4, 5}
# 移除 3 并返回剩余的集合
numbers.discard(3)
print(numbers)
# 输出: 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}
# 从集合中丢弃 3
numbers.discard(3)
print('丢弃后的集合:', numbers)
输出
丢弃后的集合: {2, 4, 5}
在上面的示例中,我们使用了 discard()
来从集合中移除一个项。结果集合中不包含项 3,因为 discard()
方法已将其移除。
示例 2:Python Set discard 一个不存在的项()
numbers = {2, 3, 5, 4}
print('丢弃前的集合:', numbers)
# 丢弃集合中不存在的项
numbers.discard(10)
print('丢弃后的集合:', numbers)
输出
丢弃前的集合: {2, 3, 4, 5}
丢弃后的集合: {2, 3, 4, 5}
在上面的示例中,我们使用了 discard()
方法丢弃集合中不存在的项。在这种情况下,原始集合 numbers 即 4 保持不变,我们不会得到任何错误。