用于从集合中删除项目的 Python 程序

programmingpythonserver side programming更新于 2025/3/14 10:52:17

在本文中,我们将学习如何从集合中删除项目。我们将看到可以轻松从集合中删除项目的不同方法。

假设我们有以下输入 -

myset = {"bmw", "tesla", "toyota", "ford", "mercedes"}

删除一个项目后,输出应如下所示 -

{'tesla', 'ford', 'bmw', 'mercedes'}

使用 remove() 方法从集合中删除项目

使用 remove() 方法,删除不在集合中的项目时会引发错误。

示例

# Creating a Set myset = {"bmw", "tesla", "toyota", "ford", "mercedes"} print("Set = \n",myset) # Applying the remove() method to remove an element myset.remove("toyota") # Display the updated Set print("\nSet (after removing an element) =\n",myset)

输出

Set = 
 {'mercedes', 'bmw', 'toyota', 'tesla', 'ford'}

Set (after removing an element) =
 {'mercedes', 'bmw', 'tesla', 'ford'}

使用 discard() 方法从集合中删除项目

使用 discord() 方法,删除不在集合中的项目不会引发错误。

示例

# Creating a Set myset = {"javascript", "php", "jquery", "angular", "react"} print("Set = \n",myset) # Applying the remove() method to remove an element myset.discard("php") # Display the updated Set print("\nSet (after removing an element) =\n",myset)

输出

Set = 
 {'javascript', 'react', 'angular', 'php', 'jquery'}

Set (after removing an element) =
 {'javascript', 'react', 'angular', 'jquery'}

使用 pop() 方法从集合中删除项目

示例

# Creating a Set myset = {"bmw", "tesla", "toyota", "ford", "mercedes"} print("Set = \n",myset) # Applying the pop() method to remove an element res = myset.pop() # Displaying the removed item print("\nRemoved item from the Set =\n",res) # Display the updated Set print("\nSet (after removing an element) =\n",myset)

输出

Set = 
 {'javascript', 'react', 'angular', 'php', 'jquery'}

Set (after removing an element) =
 {'javascript', 'react', 'angular', 'jquery'}

相关文章


有用资源