带有示例的Python Set remove()方法
设定remove()方法
remove()方法用于从集合中删除指定的元素,该方法接受一个元素并从集合中删除(如果该元素存在),如果该元素在集合中不存在,则该方法返回错误。
语法:
set_name.remove(element)
Parameter(s):
element–它表示要从列表中删除的元素。
返回值:
此方法的返回类型为<class'NoneType'>,它不返回任何内容。
范例1:
#带有示例的PythonSetremove()方法
#宣布布景
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
nums = {100, 200, 300, 400, 500}
#在移除之前打印套件
print("Before the calling remove() method...")
print("cars: ", cars)
print("nums: ", nums)
#从集合中删除元素
cars.remove("Porsche")
cars.remove("Mazda")
nums.remove(100)
nums.remove(500)
#取出后打印套件
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:
#带有示例的PythonSetremove()方法
#宣布布景
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
#打印套装
print("cars: ", cars)
#删除项目(存在于集合中)
cars.remove("Porsche")
#打印套装 again
print("cars: ", cars)
#删除项目(集合中不存在)
#它将返回错误
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'热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语