Python學習之day6 集合
阿新 • • 發佈:2017-10-26
堅持 就是勝利
python中有兩中集合類型,可變集合和不可變集合。創建集合使用set命令進行。
如下a = set (‘boy‘) 集合常用的命令有以下這些:
命令類型 | 命令描述 | 舉例說明 |
add | 添加元素到集合中(主要是把元素作為一個整體添加到集合中)添加一個 | >>> a = set(‘boy‘) >>> a.add(‘python‘) >>> a set([‘y‘, ‘python‘, ‘b‘, ‘o‘]) |
update | 添加元素到集合中(與add不同的是,它主要是把元素拆分後添加到集合中 添加多個 | >>> a.add(‘python‘) >>> a |
remove | 刪除集合裏面元素,刪除元素不在集合中,會提示報錯 | a.remove(‘python‘) |
pop | 刪除集合中的任意元素,並返回顯示該的元素 | a.pop |
union ‘|’ | 求並集(將集合合並到一起) | print(list1.union(list2) |
intersection ‘&’ | 求交集(集合之間重復出現的) | print(list1.intersection(list2) |
difference ‘-’ | 求差集(去掉集合之間重復出現的) | print list1(‘1234‘).difference(‘3456‘ ) 得到12 |
issbuset | 求子集(集合A是否屬於集合B) | print(list1.issbuset(list2))返回True或False |
issupset | 求父級(集合B是否包含集合A) | print(list1.issupset(list2))返回True或False |
symmetric_diffence ‘^‘ | 求對稱差集把兩個集合內交集部分去掉,留下剩余元素 | print(list1.symmetric_diffence(list2)) |
isdisjoint() | 如果集合之間沒有交集則返回True,否則返回False | print(list1.isdisjoint(list2)) |
in /not in | 判斷列表、字符算、字典是否在其中 | a in b |
discard | 刪除集合裏面的一個元素,如果該元素在元素中不存在,會返回為空 | a = set(‘boy‘) print a.discard(boy)沒有結果 |
本文出自 “學習筆記” 博客,請務必保留此出處http://demonlg.blog.51cto.com/7229680/1976081
Python學習之day6 集合