Python 从集合中移除项目
在本文中,我们将学习如何从集合中移除项目。我们将看到不同的方法,可以轻松地从集合中移除项目。
假设我们有以下输入 –
myset = {"bmw", "tesla", "toyota", "ford", "mercedes"}
删除一项后,输出应如下所示:
{'tesla', 'ford', 'bmw', 'mercedes'}
使用remove()方法从集合中移除项目
使用remove()方法,如果尝试移除Set中不存在的项目,则会抛出错误。
示例
# 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()方法从集合中移除元素
使用discard()方法,试图移除Set中不存在的元素时不会抛出错误。
示例
# 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'}