python集合要怎么用
pythonset集合最常用的操作是向集合中添加、删除元素,以及集合之间做交集、并集、差集等运算。
向set集合中添加元素
set集合中添加元素,可以使用set类型提供的add()方法实现,该方法的语法格式为:
setname.add(element)
其中,setname表示要添加元素的集合,element表示要添加的元素内容。
需要注意的是,使用add()方法添加的元素,只能是数字、字符串、元组或者布尔类型(True和False)值,不能添加列表、字典、集合这类可变的数据,否则Python解释器会报TypeError错误。例如:
a={1,2,3}
a.add((1,2))
print(a)
a.add([1,2])
print(a)
运行结果为:
{(1,2),1,2,3}
Traceback(mostrecentcalllast):
File"C:\Users\mengma\Desktop\1.py",line4,in
a.add([1,2])
TypeError:unhashabletype:'list'
从set集合中删除元素
删除现有set集合中的指定元素,可以使用remove()方法,该方法的语法格式如下:
setname.remove(element)
使用此方法删除集合中元素,需要注意的是,如果被删除元素本就不包含在集合中,则此方法会抛出KeyError错误,例如:
a={1,2,3}
a.remove(1)
print(a)
a.remove(1)
print(a)
运行结果为:
{2,3}
Traceback(mostrecentcalllast):
File"C:\Users\mengma\Desktop\1.py",line4,in
a.remove(1)
KeyError:1
上面程序中,由于集合中的元素1已被删除,因此当再次尝试使用remove()方法删除时,会引发KeyError错误。
如果我们不想在删除失败时令解释器提示KeyError错误,还可以使用discard()方法,此方法和remove()方法的用法完全相同,唯一的区别就是,当删除集合中元素失败时,此方法不会抛出任何错误。Python的set集合还可做交集、并集、差集运算。
以上内容为大家介绍了Python培训之集合要怎么用,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






