Python 集合 Pop() 方法

Vaibhav Vaibhav 2023年10月10日
Python 集合 Pop() 方法

集合是 Python 中的内置数据结构。存储在集合中的元素是无序且不可更改的。

无序意味着集合内的元素没有固定的顺序。不可更改意味着元素一旦添加到集合中就不能更改。

此外,集合不允许任何重复值。如果我们尝试将已经存在的值添加到集合中,它将不会被添加。

当元素从集合中弹出或移除时,我们得到最顶层的元素。我们可以使用 Python 的 pop() 方法执行弹出操作。在本文中,我们将了解这种方法。

Python 中集合的 pop() 方法

pop() 方法从 set 中弹出最顶部的元素。如果集合中不存在任何元素,则会引发以下错误。

TypeError: pop expected at least 1 arguments, got 0

请参考以下 Python 代码,借助一些相关示例了解 set() 方法的工作原理。

a = {"hello", "app", "world", "python", "qwerty"}
print("Before Popping:", a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a, end="\n\n")

a = {5, 2, 3, 1, 4}
print("Before Popping:", a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)
print("Popped Value:", a.pop())
print(a)

输出:

Before Popping: {'qwerty', 'world', 'python', 'hello', 'app'}
Popped Value: qwerty
{'world', 'python', 'hello', 'app'}
Popped Value: world
{'python', 'hello', 'app'}
Popped Value: python
{'hello', 'app'}
Popped Value: hello
{'app'}
Popped Value: app
set()

Before Popping: {1, 2, 3, 4, 5}
Popped Value: 1
{2, 3, 4, 5}
Popped Value: 2
{3, 4, 5}
Popped Value: 3
{4, 5}
Popped Value: 4
{5}
Popped Value: 5
set()
作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

相关文章 - Python Set