📅  最后修改于: 2020-10-30 06:06:34             🧑  作者: Mango
Python remove()方法从集合中删除元素elem。如果集合中不包含elem,则会引发错误KeyError。请参见下面的示例。
remove(elem)
elem:要删除的元素。
它返回None,但是如果在集合中找不到该值,则抛出KeyError。
我们来看一些remove()方法的示例,以了解其功能。
首先让我们看一个简单的示例,从集合中删除一个元素。
# Python set remove() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.remove(1)
# Displaying elements
print("After removing element: \n",set)
输出:
{1, 2, 3}
After removing element:
{2, 3}
如果该元素在集合中不可用,则会引发错误KeyError。参见示例。
Python set remove() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.remove(22)
# Displaying elements
print("After removing element: \n",set)
输出:
set.remove(22)
KeyError: 22
这种方法可以很容易地实现到程序中以执行一些业务逻辑。请参阅下面的示例。
# Python set remove() Method
# Creating a set
set = {'i','n','d','i','a','i','s','a','c','o','u','n','t','r','y'}
set2 = {'i','n','d','i','a','i','s','a','c','o','u','n','t','r','y'}
list = ['a','e','i','o','u']
# Displaying elements
print(set)
for el in set:
if el not in list:
set2.remove(el) # Removing elements which are not in list
print(set2)
输出:
{'a', 'c', 'i', 't', 'n', 'u', 'y', 's', 'd', 'o', 'r'}
{'a', 'i', 'u', 'o'}