Python Set pop:完整指南

386 阅读3分钟

Python Set pop() Method Example

Python集合pop() 方法被调用时,会从集合中移除一个随机元素。pop()方法从集合的任何地方删除任何项目。

Python set pop

set pop() 是一个内置的 Python方法,它集合中移除随机元素并返回被移除的元素。pop()方法不是从后面或前面弹出,它可以从集合中存在的任何地方弹出任何元素。

堆栈不同,随机元素是从集合中被弹出的。这是集合基本功能之一,不接受任何参数。返回值为从集合中弹出的元素。

语法

set.pop()

这里,set是集合的名称,pop()方法不接受任何参数作为参数。

返回值

set pop()方法返回被弹出的值。该值是随机弹出的。

如果这个集合是空的,它将返回一个 TypeError 异常。

例子

请看下面的代码示例。

# app.py

# Declaring sets
# Set of name
name = {'Debasis', 'Shubh', 'Shouvik', 'Rohit', 'Debanjan'}
# Set of roll numbers
roll = {24, 25, 27, 36, 40}

# printing the sets
print("Before popping name set is: ", name)
print("Before popping roll set is: ", roll)

# Now we will pop value from both the sets
print("Name which is popped: ", name.pop())
print("Roll which is popped: ", roll.pop())

# Printing the updated sets
print("Updated name set is: ", name)
print("Updated roll set is: ", roll)

print("Name which is popped: ", name.pop())
print("Roll which is popped: ", roll.pop())

# Printing the updated sets
print("Updated name set is: ", name)
print("Updated roll set is: ", roll)

输出

Before popping name set is:  {'Rohit', 'Shouvik', 'Debanjan', 'Debasis', 'Shubh'}
Before popping roll set is:  {36, 40, 24, 25, 27}
Name which is popped:  Rohit
Roll which is popped:  36
Updated name set is:  {'Shouvik', 'Debanjan', 'Debasis', 'Shubh'}
Updated roll set is:  {40, 24, 25, 27}
Name which is popped:  Shouvik
Roll which is popped:  40
Updated name set is:  {'Debanjan', 'Debasis', 'Shubh'}
Updated roll set is:  {24, 25, 27}

我们可以看到,当我们打印这个集合时,数值是根据给定的输入数据显示的。它们是随机显示的。

同样地,当我们弹出数值时,它也是随机弹出的数值。我们已经弹出了两次数值,每次都打印了更新的集合。

虽然我的电脑是从前面弹出的值,但在你的情况下,可能是不同的,每次你运行这个程序,你会得到不同的答案。所以如果你的答案不同,请不要感到困惑。

在空集上操作pop()方法

让我们在空集上操作pop()方法。

# app.py

# Declaring empty set
# Set of name
name = {}


# Now we will pop value from both the sets
print("Name which is popped: ", name.pop())

输出

python3 app.py
Traceback (most recent call last):
  File "app.py", line 7, in <module>
    print("Name which is popped: ", name.pop())
TypeError: pop expected at least 1 arguments, got 0

在Python混合集上操作pop()方法

让我们声明一个混合集合,并使用集合的pop方法从一个集合中删除一个随机项。

# app.py

mixed_set = {'Stranger Things', 11, 'Rick and Morty',
             21, 'The Witcher', 46, 'Education'}
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)

输出

python3 app.py
The Original Set :  {'Education', 'Stranger Things', 11, 'The Witcher', 46, 'Rick and Morty', 21}

pop Item         :  Education
The Set after pop:  {'Stranger Things', 11, 'The Witcher', 46, 'Rick and Morty', 21}

pop Item         :  Stranger Things
The Set after pop:  {11, 'The Witcher', 46, 'Rick and Morty', 21}

本教程到此结束。