python-11 資料結構 - 集合
阿新 • • 發佈:2018-11-11
分類
可變集合: 建立 字面量建立 {值} 值: 整形 字串 元組 只能是固定型別,不可以是列表,可以是元組 >>> {1,2,3,} {1, 2, 3} >>> {1,"s"} {1, 's'} >>> {1,1.2,True} {1, 1.2} >>> {11,True} {True, 11} 通過物件建立 set() >>> set2 = set("hello") >>> set <class 'set'> >>> set2 {'l', 'e', 'h', 'o'} >>> set3 = set([1,2,3,4]) >>> set3 {1, 2, 3, 4} frozenset() >>> set3 = frozenset("hello") >>> set3 frozenset({'l', 'e', 'h', 'o'}) 推導式 >>> {x*x for x in range(5)} {0, 1, 4, 9, 16} 不可變集合:
交集
>>> {1,False}
{False, 1}
>>> {1,1.0}
{1}
>>> {1,True}
{1}
集合的操作
遍歷訪問: >>> set1 = {1,2,3,6,7,8,5,4} >>> for i in set1: print(i,end="") 12345678 成員判斷 in not in >>> set1={1,2,3} >>> set2 = {2,3,4,5,6} 並集 >>> set1| set2 {1, 2, 3, 4, 5, 6} 交集 >>> set1 & set2 {2, 3} 差集 >>> set1 - set2 {1} 對差 >>> set1 ^ set2 {1, 4, 5, 6} >>> set1==set2 False >>> set1>set2 False >>> set1<set2 False >>> len(set1) 3 集合的合併 >>> set1 {1, 2, 3} >>> set2 {2, 3, 4, 5, 6} >>> set1.update(set2) >>> set1 {1, 2, 3, 4, 5, 6} copy(): >>> set1 {1, 2, 3, 4, 5} >>> set2 = set1.copy() >>> set2 {1, 2, 3, 4, 5}
不支援索引