被我忽略許久的set
心塞,set一直是我忽略的一個數據結構
1.生成一個set:
1) set(iterable)
傳入一個可以叠代的數據結構:
eg:字符串;元組;列表,字典
2) {v1,v2,.......,vn}
註意:vi必須是可以哈希的:
你問我啥叫哈希.額,你就知道就是不能變的就好了,剩下的問題問度娘
或者參考http://www.cnblogs.com/chenzhaosu/articles/3506790.html
3) 創建一個空set
set()
2.set的特點:
1)無序
2)不重復
3)可變
3.方法
add() difference_update()
clear() discard()
copy() intersection() >
difference() intersection_update()
‘add‘,
‘clear‘,
‘copy‘,
‘difference‘,
‘difference_update‘,
‘discard‘,
‘intersection‘,
‘intersection_update‘,
‘isdisjoint‘,
‘issubset‘,
‘issuperset‘,
‘pop‘,
‘remove‘,
‘symmetric_difference‘,
‘symmetric_difference_update‘,
‘union‘,
‘update‘
1)查:
無序啊,怎麽查.遍歷吧
2)增:
add()
eg:
In [3]: a
Out[3]: {‘e‘, ‘h‘, ‘l‘, ‘o‘}
In [4]: a.add("kkkk")
In [5]: a
Out[5]: {‘e‘, ‘h‘, ‘kkkk‘, ‘l‘, ‘o‘}
update()
eg:
In [7]: a.update("world")
In [8]: a
Out[8]: {‘d‘, ‘e‘, ‘h‘, ‘kkkk‘, ‘l‘, ‘o‘, ‘r‘, ‘w‘}
3)刪:
pop()
eg:
In [9]: a.pop()
Out[9]: ‘e‘
remove()
eg:
In [13]: a
Out[13]: {‘d‘, ‘kkkk‘, ‘l‘, ‘o‘, ‘r‘, ‘w‘}
In [14]: a.remove("kkkk")
In [15]: a
Out[15]: {‘d‘, ‘l‘, ‘o‘, ‘r‘, ‘w‘}
4應用:
兩個應用場景,1)去重,2)關系測試(數學裏面的集合關系)
1)去重
eg:
l = [1,2,3,4,1,2,5,6]
得到不重復的列表:
In [16]: l = [1,2,3,4,1,2,5,6]
In [17]: l_new=list(set(l))
In [18]: l_new
Out[18]: [1, 2, 3, 4, 5, 6]
2)關系測試(可以參考數學上的集合關系)
eg:
set1={1,2,3,4,5}
set2={4,5,6,7,8}
a)取並集
In [22]: set1.union(set2)
Out[22]: {1, 2, 3, 4, 5, 6, 7, 8}
In [24]: set1 |set2
Out[24]: {1, 2, 3, 4, 5, 6, 7, 8}
b)取交集
In [25]: set1.intersection(set2)
Out[25]: {4, 5}
In [26]: set1 &set2
Out[26]: {4, 5}
c)取差集
①)在set1中不在set2中
In [27]: set1.difference(set2)
Out[27]: {1, 2, 3}
In [28]: set1-set2
Out[28]: {1, 2, 3}
②)在set2中不在set1中
In [29]: set2.difference(set1)
Out[29]: {6, 7, 8}
In [30]: set2-set1
Out[30]: {6, 7, 8}
d)(set1 U set2)-(set1 n set2)
In [31]: set1.symmetric_difference(set2)
Out[31]: {1, 2, 3, 6, 7, 8}
In [32]: set1^set2
Out[32]: {1, 2, 3, 6, 7, 8}
註: ^ 為數字6上的符號
e)子集,超級
eg:
In [33]: s1={1,2,3}
In [34]: s2={1,2}
In [42]: s2.issubset(s1)
Out[42]: True
自己是本身的子集
In [45]: s1.issuperset(s2)
Out[45]: True
In [46]: s1.issuperset(s1)
Out[46]: True
In [47]: s1<s2
Out[47]: False
In [48]: s1>s2
Out[48]: True
In [49]: s1<s1
Out[49]: False
In [50]: s1>s1
Out[50]: False
註意:使用符號的表示的時候嚴格小於和大於
In [51]: s1>=s1
Out[51]: True
被我忽略許久的set