集合就类似于数学中的集合,具有互异性和无序性。
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} >>>