1. 程式人生 > >Python學習之day6 集合

Python學習之day6 集合

堅持 就是勝利

python中有兩中集合類型,可變集合和不可變集合。創建集合使用set命令進行。

如下a = set (‘boy‘) 集合常用的命令有以下這些:


命令類型命令描述舉例說明
add添加元素到集合中(主要是把元素作為一個整體添加到集合中)添加一個>>> a = set(‘boy‘)
>>> a.add(‘python‘)
>>> a
set([‘y‘, ‘python‘, ‘b‘, ‘o‘])
update添加元素到集合中(與add不同的是,它主要是把元素拆分後添加到集合中 添加多個
>>> a.add(‘python‘)
>>> a
set([ ‘p,‘y‘,‘t‘,‘h‘,‘n‘, ‘o‘])
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,否則返回Falseprint(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 集合