本文共 2085 字,大约阅读时间需要 6 分钟。
python 示例
remove() method is used to remove a specified element from the set, the method accepts an element and removes from the set if it exists, if the element does not exist in the set, the method returns an error.
remove()方法用于从集合中删除指定的元素,该方法接受一个元素并从集合中删除(如果存在),如果该元素在集合中不存在,则该方法返回错误。
Syntax:
句法:
set_name.remove(element)
Parameter(s):
参数:
element – It represents the element to be removed from the list.
element –它表示要从列表中删除的元素。
Return value:
返回值:
The return type of this method is <class 'NoneType'>, it returns nothing.
此方法的返回类型为<class'NoneType'> ,它什么也不返回。
Example 1:
范例1:
# Python Set remove() Method with Example# declaring the setscars = { "Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}nums = { 100, 200, 300, 400, 500}# printing the sets before removingprint("Before the calling remove() method...")print("cars: ", cars)print("nums: ", nums)# Removing the elements from the setscars.remove("Porsche")cars.remove("Mazda")nums.remove(100)nums.remove(500)# printing the sets after removingprint("After the calling remove() method...")print("cars: ", cars)print("nums: ", nums)
Output
输出量
Before the calling remove() method...cars: {'Mazda', 'Audi', 'Porsche', 'Lexus', 'Lincoln'}nums: {100, 200, 300, 400, 500}After the calling remove() method...cars: {'Audi', 'Lexus', 'Lincoln'}nums: {200, 300, 400}
Demonstrating example, how method raises error if element is not find in the set?
演示示例,如果在集合中找不到元素,方法将如何引发错误?
Example 2:
范例2:
# Python Set remove() Method with Example# declaring the setscars = { "Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}# printing the setprint("cars: ", cars)# removing an item (which exists in the set)cars.remove("Porsche")# printing the set againprint("cars: ", cars)# removing an item (which does not exist in the set)# it will return an errorcars.remove("BMW")
Output
输出量
cars: {'Mazda', 'Audi', 'Lexus', 'Porsche', 'Lincoln'}cars: {'Mazda', 'Audi', 'Lexus', 'Lincoln'}Traceback (most recent call last): File "main.py", line 15, incars.remove("BMW")KeyError: 'BMW'
翻译自:
python 示例
转载地址:http://xgazd.baihongyu.com/