Python 集合 pop 方法

Python pop 方法用于从集合中移除一个随机元素。这是因为集合不会使用索引来存储项。您可以将该移除的元素赋给一个新变量以供进一步引用。此集合 pop 方法的语法是:

set.pop()

Python set pop 函数示例

pop 方法从给定的集合中移除最后一个元素。众所周知,集合没有任何特定的顺序。因此,您永远不知道哪个元素被移除了。在此示例中,我们声明了一个数字集合。接下来,我们使用 pop 函数从现有集合中移除一个随机集合项。

numeric = {150, 250, 350, 450, 550}
 
print('The Original : ', numeric )
 
numeric.pop()

print('The after : ', numeric)
The Original :  {450, 550, 150, 250, 350}
The after :  {550, 150, 250, 350}

此代码与上述示例相同。但是,这次我们将移除的值赋给了一个新变量并打印出来。

提示:请参阅 Python 中的 集合Python 教程

numeric = {150, 250, 350, 450, 550}
 
print('The Original : ', numeric )
 
x = numeric.pop()
 
print('\npop Item      : ', x)

print('The after : ', numeric)
The Original :  {450, 550, 150, 250, 350}

pop Item      :  450
The after :  {550, 150, 250, 350}

如何使用 set pop 移除所有元素?

在此 Python 集合 pop 示例中,我们使用它逐个移除所有现有元素。

numeric_set = {15, 25, 35, 45, 55}
print('The Original  : ', numeric_set )
 
x = numeric_set.pop()
print('\npop Item      : ', x)
print('The Set after : ', numeric_set)
 
y = numeric_set.pop()
print('\npop Item      : ', y)
print('The Set after : ', numeric_set)
 
z = numeric_set.pop()
print('\npop Item      : ', z)
print('The Set after : ', numeric_set)
 
zz = numeric_set.pop()
print('\npop Item      : ', zz)
print('The Set after : ', numeric_set)
The Original  :  {35, 55, 25, 45, 15}

pop Item      :  35
The Set after :  {55, 25, 45, 15}

pop Item      :  55
The Set after :  {25, 45, 15}

pop Item      :  25
The Set after :  {45, 15}

pop Item      :  45
The Set after :  {15}

如何从字符串集合中 pop 元素?

这次我们正在字符串集合上使用 pop 函数。

fruits_set = {'Mango', 'Cherry', 'Apple', 'Kiwi'}
print('The Original : ', fruits_set)
 
x = fruits_set.pop()
print('pop Item         : ', x)
print('The after: ', fruits_set)
 
y = fruits_set.pop()
print('\npop Item         : ', y)
print('The after : ', fruits_set)
The Original :  {'Apple', 'Mango', 'Cherry', 'Kiwi'}
pop Item         :  Apple
The after:  {'Mango', 'Cherry', 'Kiwi'}

pop Item         :  Mango
The after :  {'Cherry', 'Kiwi'}

虽然这不值得,但我还是给出一个示例。这样您就能明白。

a = {1, 2, 3, 4, 5, 6, 7, 8, 9}
print("Old Items = ", a)

a.discard(7)
a.discard(4)
print("New Set Items = ", a)

Fruits = {'apple', 'Mango', 'orange', 'banana', 'cherry','kiwi'}
print("\nOld Items = ", Fruits)

Fruits.discard('Mango')
print("New Items = ", Fruits)
Old Items = {1, 2, 3, 4, 5, 6, 7, 8, 9}
New Items = {1, 2, 3, 5, 6, 8, 9}

Old Items = {'Mango', 'cherry', 'banana', 'apple', 'kiwi', 'orange'}
New Items = {'cherry', 'banana', 'apple', 'kiwi', 'orange'}

如何从混合集合中 pop 元素?

在这里,我们声明了混合元素。接下来,我们使用 pop 方法从中移除一个随机元素。

mixed_set = {'Mango', 10, 'Cherry', 20, 'Apple', 30, 'Kiwi'}
print('The Original Set : ', mixed_set)
 
x = mixed_set.pop()
print('\npop Item         : ', x)
print('The Set after pop: ', mixed_set)
 
y = mixed_set.pop()
print('\npop Item         : ', y)
print('The Set after pop: ', mixed_set)
set pop method