pop()
方法从集合中移除一个项目并返回被移除的项目。
示例
A = {'a', 'b', 'c', 'd'}
removed_item = A.pop()
print(removed_item)
# Output: c
pop() 语法
pop()
方法的语法是
set.pop()
这里,pop()
从 set 中移除一个项目并更新它。
pop() 参数
pop()
方法不接受任何参数。
pop() 返回值
pop()
方法返回
- 从集合中移除的项目
- 如果集合为空,则抛出
TypeError
异常
示例 1:Python 集合 pop()
A = {'10', 'Ten', '100', 'Hundred'}
# removes random item of set A
print('Pop() removes:', A.pop())
# updates A to new set without the popped item
print('Updated set A:', A)
输出
Pop() removes: 10 Updated set A: {'Ten', '100', 'Hundred'}
在上面的示例中,我们使用 pop()
移除了集合 A 中的项目。这里,pop()
从集合 A 中移除了 10 并返回它。
此外,集合 A 更新为一个不含被移除项目 10 的新集合。
注意:每次运行它时,我们可能会得到不同的输出,因为 pop()
返回并移除一个随机元素。
示例 2:空集合的 pop()
# empty set
A ={}
# throws an error
print(A.pop())
输出
TypeError: pop expected at least 1 argument, got 0
在上面的示例中,我们对空集合 A 使用了 pop()
。该方法无法从空集合中移除任何项目,因此会抛出错误。
另请阅读