Python 集合 pop()方法
Python的pop()方法从集合中弹出一个元素。它不接受任何参数,但返回弹出的元素。如果集合中不存在该元素,则会引发错误。下面是该方法的示例和签名。
语法
pop()
参数
无参数。
返回值
如果集合为空,则返回删除的元素或抛出错误。
让我们看一些pop()方法的例子,以了解它的功能。
示例1
一个简单的例子,使用pop()方法删除一个元素并修改集合。
# Python set pop() Method
# Creating a set
set = {1,2,3,4,5}
# Displaying elements
print(set)
# Calling function
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
输出:
{1, 2, 3, 4, 5}
Element popped: 1
Remaining elements: {2, 3, 4, 5}
Element popped: 2
Remaining elements: {3, 4, 5}
Element popped: 3
Remaining elements: {4, 5}
Element popped: 4
Remaining elements: {5}
示例2
如果集合为空,则抛出KeyError错误给调用函数。请参见示例。
# Python set pop() Method
# Creating a set
set = {1,2}
# Displaying elements
print(set)
# Calling function
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
输出:
{1, 2}
Element popped: 1
Remaining elements: {2}
Element popped: 2
Remaining elements: set()
Traceback (most recent call last):
File "main.py", line 13, in
el = set.pop()
KeyError: 'pop from an empty set'
示例3
该示例包含了按顺序添加和弹出元素来描述该方法的功能。
# Python set pop() Method
# Creating a set
set = {1,2}
# Displaying elements
print(set)
# Calling function
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
set.add(4)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
set.add(5)
el = set.pop()
print("Element popped:",el)
print("Remaining elements: ",set)
输出:
{1, 2}
Element popped: 1
Remaining elements: {2}
Element popped: 2
Remaining elements: {4}
Element popped: 4
Remaining elements: {5}