- A+
所属分类:Python学习
Python3集合说明:
用花括号包含没有体现映射关系,即称为集合。
a为字典,而b因为没有映射关系,所以被称为集合。
- a = {1:12,2:12,3:13,4:14,5:15,6:16}
- b = {1,2,3,4,5,6}
- print(type(a),type(b)) # <class 'dict'> <class 'set'>
Python3集合练习
集合天生具备一个功能,就是所有值是唯一的,通俗点也可以理解为去重。
- 用for循环筛选出重复的内容
- f = [1,2,3,4,5,5,3,1,0]
- temp =[]
- for each in f:
- if each not in temp:
- temp.append(each)
- print(temp)
- 用集合去除
- e =list(set(f))
Python3集合常见方法:
- 集合的创建
- 使用花括号创建
- 使用set函数创建
- 集合中数据的访问
因为集合和字典相同都是无序的,所以无法使用下标的方式获取到其内容,但是可以与字典一样可以通过成员操作来获取到数据。
- e = [1,2,3,4,5,5,3,1,0]
- if 10 in e:
- print('在')
- else:
- print('不在')
- 集合中数据的增加
- e = {1, 2, 3, 4, 5}
- e.add(6)
- print(e) #{1, 2, 3, 4, 5, 6}
- 集合中数据的清除
1、remove
移动集合中的一个指定元素,指定元素未包含的集合中,返回KeyError。
2、discard
与remove功能差不多,不同点指定元素未包含的集合中,不报错。
3、pop
移除并返回e中的任意一个元素
4、clear
清除集合中的全部元素
- e.remove(5)
- print(e) #{1, 2, 3, 4, 6}
- # e.remove(8) KeyError: 8,未包含8,报错
- # 丢弃操作,与remove不同是,未包含的内容,不报错
- e = {1, 2, 3, 4, 5}
- e.discard(10)
- print(e) #{1, 2, 3, 4, 5}
- e = {1, 2, 3, 4, 5}
- print(e.pop()) #移除并返回e中的任意一个元素
- print(e)
- e = {1, 2, 3, 4, 5}
- print(e.clear()) #清楚e中的所有元素
- print(e)
- 不可变集合
- e = {1, 2, 3, 4, 5}
- f = frozenset(e)
- f.add(10)
- print(f) # AttributeError: 'frozenset' object has no attribute 'add'
- update
- e = {1, 2, 3, 4, 5}
- g = {'a','b','c',1,2,3}
- e.update(g)#将g中包含的元素添加到e中
- print(e)
- intersection_update
- e = {1, 2, 3, 4, 5}
- g = {'a','b','c',1,2,3}
- e.intersection_update(g) #交集修改:g和e包含的相同元素
- print(e)
- difference_update
- e = {1, 2, 3, 4, 5}
- g = {'a','b','c',1,2,3}
- e.difference_update(g) #差修改:去除e中g包含的元素
- print(e)
- symmetric_difference_update
- e = {1, 2, 3, 4, 5}
- g = {'a','b','c',1,2,3}
- e.symmetric_difference_update(g) #对称差分修改,e中仅属于e或者g的成员
- print(e)
- 浅拷贝
- e = {1, 2, 3, 4, 5}
- H = e.copycopy() #返回e的一个浅拷贝
- print(H)
- 操作符
- e = {1, 2, 3, 4, 5}
- g = {1, 2, 3}
- print(e.issubset(g)) # False 测试是否 e 中的每一个元素都在 g 中
- print(e <= g) # False
- print(e.issuperset(g)) # True 测试是否 g 中的每一个元素都在 e 中
- print(e >= g) # True
- print(e.union(g)) # 合并操作:e或g中的元素
- print(e | g) # 合并操作:e或g中的元素
- print(e.intersection(g))
- print(e & g) # 交集操作:e与g中的元素
- print(e.difference(g)) # 差分操作:在e中存在,在g不存在
- print(e - g) # 差分操作:在e中存在,在g不存在
- print(e.symmetric_difference(g)) # 返回一个新的 set 包含 e 和 g 中不重复的元素
- print(e ^ g) # 返回一个新的 set 包含 e 和 g 中不重复的元素
单词扩展:
- frozen:冰冻的,冻结的
- update : 更新
- symmetric : 对称
- difference :差异
- intersection :交叉
- union : 联合
扩展阅读:
版权注释:
Python课程来源于鱼C论坛:http://bbs.fishc.com/forum-243-1.html 版块,课程内容为免费内容,如果你喜欢该课程,建议购买VIP账号支持小甲鱼,官方网店:https://fishc.taobao.com/)。
本内容为在李金龙在学习课程中做的日记记录,方便自己以后查找相关信息,另一方面也希望自己写下的东西可以帮助到别人。
课程内容:http://blog.fishc.com/3270.html