Python的集合數據結構詳解
建立一個集合
本例Python版本為Python3.4
>>> set([1, 2, 3, 4]) # 內置函數
>>> {1, 2, 3, 4}
集合中的值不可更改,但是還是可以向集合中添加元素的
集合中的元素是無序的,唯一的(該特性經常用於去重)
C:\code> c:\python34\python
>>> set([1, 2, 3, 4])
{1, 2, 3, 4}
>>> set('spam')
{'s', 'a', 'p', 'm'}
>>> {1, 2, 3, 4}
{1, 2, 3, 4}
>>> S = {'s', 'p', 'a', 'm'}
>>> S
{'s', 'a', 'p', 'm'}
集合中添加元素
>>> S = set() # 初始化一個空的集合
>>> S.add(1.23)
>>> S
{1.23}
集合的 交,並,補,子集
>>> engineers = {'bob', 'sue', 'ann', 'vic'}
>>> managers = {'tom', 'sue'}
>>> 'bob' in engineers # in操作符
True
>>> engineers & managers #交集
{'sue'}
>>> engineers | managers #並集
{'bob', 'tom', 'sue', 'vic', 'ann'}
>>> engineers - managers
{'vic', 'ann', 'bob'}
>>> managers - engineers
{'tom'}
>>> engineers > managers #超集
False
>>> {'bob', 'sue'} < engineers #子集
True
>>> (managers | engineers) > managers
True
>>> managers ^ engineers
# 只有一種職務,而不是身兼兩職,類似於xor(比特操作)
{'tom', 'vic', 'ann', 'bob'}
>>> {1, 2, 3} | {3, 4}#並集
{1, 2, 3, 4}
>>> {1, 2, 3} | [3, 4]
TypeError: unsupported operand type(s) for |: 'set' and 'list'
#並集操作只能應用於兩個集合,而不能是一個集合,一個是列表
>>> {1, 2, 3}.union([3, 4])
{1, 2, 3, 4}
>>> {1, 2, 3}.union({3, 4})
{1, 2, 3, 4}
>>> {1, 2, 3}.union(set([3, 4]))
{1, 2, 3, 4}
>>> {1, 2, 3}.intersection((1, 3, 5))#交集
{1, 3}
>>> {1, 2, 3}.issubset(range(-5, 5))#子集
True
集合用來過濾序列中重複元素
>>> L = [1, 2, 1, 3, 2, 4, 5]
>>> set(L)
{1, 2, 3, 4, 5}
>>> L = list(set(L)) # 去重
>>> L
[1, 2, 3, 4, 5]
>>> list(set(['yy', 'cc', 'aa', 'xx', 'dd', 'aa']))
# 順序可能會變化
['cc', 'xx', 'yy', 'dd', 'aa']
判斷集合相等
>>> L1, L2 = [1, 3, 5, 2, 4], [2, 5, 3, 4, 1]
>>> L1 == L2 # 序列是有順序的
False
>>> set(L1) == set(L2)# 集合沒有順序
True
>>> sorted(L1) == sorted(L2)
# 排序之後
True
>>> 'spam' == 'asmp', set('spam') == set('asmp'), sorted('spam') == sorted('asmp')
(False, True, True)