打开《Python入门与实战》_一步步学会Python_8.4.2 案例解析
145
2023-10-19
【摘要】 本书摘自《Python3快速入门与实战》一书中第3章,第4节,由肖冠宇、杨捷等编著。
3.4.2 成员运算符在集合中的应用
判断一个元素在集合中是否存在可以使用Python 内置的成员运算符 in 或者 not in, 成员 运算符的返回值是布尔类型值True或Flase。
例3-36 判断一个学生的学号在存储学生学号的集合中是否存在(源代码位置: chapter03/ 3.4集合.py)。
案例代码如下:
student id set={"20180101","20180102","20180103","20180104"}
student id="20180102"
if student id in student id set:
_ _ _
print("O学号存在!".format(student id)
if student id not in student id set:
_ _ _
print("}学号不存在!".format(student id))
运行结果如下:
20180102学号存在!
20180108学号不存在!
3.4.3 向集合中添加元素
1. add()方法
使 用 add()方法可以将一个元素添加到集合中。注意: add()方法是把要添加的元素作为 整体添加到集合中。
例3-37 使 用 add()方法将一个新同学的学号添加到存储学号的集合中(源代码位置: chapter03/3.4 集合.py)。
案例代码如下:
#存储学生学号的集合
student id set={"20180101","20180102","20180103","20180104"}
#使用add方法把一个元素作为整体添加到集合中
student id set.add("20180105")
print(student id set)
运行结果如下:
{'20180105','20180104','20180103','20180101','20180102'}
2.update()方法
使用update()方法将序列中的每个元素添加到集合中,并对集合中的元素去重。序列 可以是列表、元组、字典等。如果需要向 update()方法中传入多个序列,则序列之间用逗 号隔开。
例3-38 使 用 update()方法将不同序列中存储的学号添加到存储学号的集合中(源代码 位置: chapter03/3.4集 合 .py)。
案例代码如下:
#将列表中的每一个元素作为整体添加进集合,同时对元素去重
studen t id set.update(["20180106","20180107","20180106"])
print("update列表:",student id set)
#将元组中的每一个元素作为整体添加进集合,同时对元素去重
student id set.update(("20180108","20180109"))
print("update元组:",student id set)
#把一个集合并到另外一个集合
student id set new ={"20180110","20180111"}
student id set.update(student id set new)
print("update 合并集合:",student id set)
#多个序列添加到集合中,使用逗号分隔,同时对所有序列中的元素去重
student id set.update(["20180112","20180113"],["20180113","20180114","20180115"]) print("update 合并集合:",student id set)
#如果向update中传入一个字符串,会把字符串按字符拆开,分别添加到集合中
student id set.update("0000000")
print("update 字符串:",student id set)
运行结果如下:
update列表: {'20180106,20180102','20180103','20180107','20180104,'20180101'
update 元组:{20180106,'20180108','20180102','20180103','20180107,20180109,'20180104,
'20180101'
update 合并集合: {'20180106,20180108','20180102','20180110,'20180103',20180107','20180111', '20180109','20180104','20180101'
update 合并集合:{'20180106,'20180108','20180114',20180102','20180115','20180110,20180103', '20180107,'20180112','20180113','20180111','20180109,'20180104,'20180101
update 字符串: {'20180106,'20180108',20180114,20180102','20180115','20180110,'20180103', '20180107','20180112','20180113','20180111','20180109','0','20180104','20180101
注意: 运行结果的最后一行,当把字符串作为参数传入 update() 方法时, update() 方法 把字符串作为序列处理,拆分出组成字符串的元素0分别添加到集合中,由于集合需要对元 素去重,所以在student id set集合中只存在一个0.
3.4.4 删除集合中的元素
1. remove()方法
根据元素值使用 remove()方法删除集合中指定的元素,如果要删除的元素不存在,则程 序会报错。
例3-39 使用 remove()方法删除存储学号集合中的“20180101”学号(源代码位置: chapter03/3.4集合.py)。
案例代码如下:
student id set={"20180101","20180102","20180103","20180104"}
#删除学号20180101
student id set.remove("20180101")
print("执行remove 方法后:",student id set)
#再次删除学号20180101将报错
student id set.remove("20180101")
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们 18664393530@aliyun.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~