Python的這種內置函數有助於在實現Stack時從集合中彈出元素,就像概念中使用的原理一樣。此方法從集合中刪除隨機元素,然後返回刪除的元素。與之不同的是,堆棧中會彈出一個隨機元素。
用法:
# Pops a random element from S # and returns it. S.pop()
這是集合的基本函數之一,不接受任何參數。返回值是集合中彈出的元素。一旦將元素從集合中彈出,該集合將丟失該元素,並將其更新為不包含該元素的集合。
例子:
Input: sets = {1, 2, 3, 4, 5} Output: 1 Updated set is {2, 3, 4, 5} Input: sets = {"ram", "rahim", "ajay", "rishav", "aakash"} Output: rahim Updated set is {'ram', 'rishav', 'ajay', 'aakash'}
# Python code to illustrate pop() method
S = {"ram", "rahim", "ajay", "rishav", "aakash"}
# Popping three elements and printing them
print(S.pop())
print(S.pop())
print(S.pop())
# The updated set
print("Updated set is", S)
輸出:
rishav ram rahim Updated set is {'aakash', 'ajay'}
另一方麵,如果集合為空,則返回TypeError,如以下程序所示。
# Python code to illustrate pop() method
# on an empty set
S = {}
# Popping three elements and printing them
print(S.pop())
# The updated set
print("Updated set is", S)
輸出:
No Output
錯誤:
Traceback (most recent call last): File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in print(S.pop()) TypeError:pop expected at least 1 arguments, got 0
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Python Set | pop()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。