当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Set remove()用法及代码示例


设置 remove() 方法

remove() 方法用于从集合中移除指定元素,该方法接受一个元素,如果存在则从集合中移除,如果该元素在集合中不存在,则该方法返回错误。

用法:

    set_name.remove(element)

参数:

  • element– 它表示要从列表中删除的元素。

返回值:

这个方法的返回类型是<class 'NoneType'>,它什么都不返回。

范例1:

# Python Set remove() Method with Example

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
nums = {100, 200, 300, 400, 500}

# printing the sets before removing
print("Before the calling remove() method...")
print("cars:", cars)
print("nums:", nums)

# Removing the elements from the sets
cars.remove("Porsche")
cars.remove("Mazda")

nums.remove(100)
nums.remove(500)

# printing the sets after removing
print("After the calling remove() method...")
print("cars:", cars)
print("nums:", nums)

输出

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}

演示示例,如果在集合中找不到元素,方法如何引发错误?

范例2:

# Python Set remove() Method with Example

# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}

# printing the set
print("cars:", cars)
# removing an item (which exists in the set)
cars.remove("Porsche")
# printing the set again
print("cars:", cars)

# removing an item (which does not exist in the set)
# it will return an error
cars.remove("BMW")

输出

cars: {'Mazda', 'Audi', 'Lexus', 'Porsche', 'Lincoln'}
cars: {'Mazda', 'Audi', 'Lexus', 'Lincoln'}
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    cars.remove("BMW")
KeyError:'BMW'


相关用法


注:本文由纯净天空筛选整理自 Python Set remove() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。