PYTHON-set()-集合学习
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PYTHON-set()-集合学习,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2364字,纯文字阅读大概需要4分钟。
内容图文
集合就类似于数学中的集合,具有互异性和无序性。
1.创建集合:
#创建一个空的集合必须用set(),因为{}为dict。且set()只接受一个参数
>>> a = {} >>> type(a) <class‘dict‘> >>> a = set() >>> type(a) <class‘set‘> >>>
#集合中放的只能是数字、元组、字符串,不能放字典,列表
>>> set1 = {1, 2, 3, (4, 5, 6), "good news",[1,2,3]} Traceback (most recent call last): File "<pyshell#83>", line 1, in <module> set1 = {1, 2, 3, (4, 5, 6), "good news",[1,2,3]} TypeError: unhashable type: ‘list‘ >>> set1 = {1, 2, 3, (4, 5, 6), "good news"} >>> set1 {‘good news‘, 1, 2, 3, (4, 5, 6)} >>> set1 = {1, 2, 3, (4, 5, 6), "good news",{1:"123",2:"456"}} Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> set1 = {1, 2, 3, (4, 5, 6), "good news",{1:"123",2:"456"}} TypeError: unhashable type: ‘dict‘
#但是单个的字典、集合、列表还是可以的
>>> a = set([1,2,3]) >>> a {1, 2, 3} >>> a = set({1,2,3}) >>> a {1, 2, 3} >>> a = set({1:"123",2:"456"}) >>> a {1, 2}
#组合起来就不行了
>>> a = set({[1,2,3]}) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> a = set({[1,2,3]}) TypeError: unhashable type: ‘list‘ >>> a = set({[1,2,3],(1,)}) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> a = set({[1,2,3],(1,)}) TypeError: unhashable type: ‘list‘ >>>
2.作用
2.1 列表过滤:
#可以将列表中的重复元素过滤掉,很简单的
>>> a = [1,1,1,2,3,6,5,8,6,2] >>> set(a) {1, 2, 3, 5, 6, 8} >>> list(set(a)) [1, 2, 3, 5, 6, 8]
2.2 add(值)
>>> c = {1,3} >>> c.add(2) >>> c {1, 2, 3} #增肌爱元素的无序性,就是没加在最后 >>> c.add(2) >>> c {1, 2, 3} #互异性
2.3 remove(值)
>>> c {1, 2, 3} >>> c.remove(2) >>> c {1, 3} >>> c.remove(5) Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> c.remove(5) KeyError: 5 >>>
2.4 集合运算:
>>> a = {1,2,34,58} >>> b = {1,3,7,6} >>> a & b #交集 {1} >>> a | b #并集 {1, 2, 34, 3, 6, 7, 58} >>> a - b #a中a&b的补集 {2, 34, 58} >>> b -a #b中a&b的补集 {3, 6, 7} >>>
参考网址:
https://www.cnblogs.com/my_captain/p/9296282.html
https://www.cnblogs.com/TTyb/p/6283539.html
原文:https://www.cnblogs.com/xiao-yu-/p/12627246.html
内容总结
以上是互联网集市为您收集整理的PYTHON-set()-集合学习全部内容,希望文章能够帮你解决PYTHON-set()-集合学习所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。