📅  最后修改于: 2020-10-30 06:04:46             🧑  作者: Mango
Python pop()方法从集合中弹出一个元素。它不带任何参数,但返回弹出的元素。如果该元素不存在于集合中,则会引发错误。请参见示例,下面给出了该方法的签名。
pop()
没有参数。
它返回已删除的元素,或者如果集合为空则抛出错误。
我们来看一些pop()方法的示例,以了解其功能。
一个使用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}
如果集合为空,则会向调用者函数抛出错误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'
此示例按顺序包含添加和弹出元素以描述其功能。
# 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}