集合
set(集合)是一個無需不重複的元素數據集,對比列表的區別首先是無需的,不可以使用索引進行訪問,另外一個特點是不能有重複數據。
項目開發中,集合主要用於數據元素去重和測試是否存在。集合還支持一些數學上的運算,例如:union(聯合)、intersection(交)、difference(差)、symmetric difference(對稱差集)。
創建集合:
集合使用大括號或者set函數創建,需要注意空的集合不能使用{}創建,只能使用set函數,因爲{}創建的是一個空字典。
>> courses = set()
>> type(courses)
<class 'set'>
>> courses = {'linux','C++','Vim','Linx'}
>> courses
{'C++', 'Vim', 'Linx', 'linux'} #重複的‘linux’字符串已被自動去除
集合還可以直接由字符串與set函數進行創建,會將字符串拆分爲不同的字符,並去除重複的字符:
>> nameset = set('python3')
>> nameset
{'p', 'n', 'o', '3', 'h', 't', 'y'}
集合操作:
集合去重,使用in判斷(in也適用於列表和元組):
>> 'linux' in courses
True
>> 'python' in courses
False
>> 'python' not in courses
True
add()向集合中增加元素,使用remove()從集合中刪除元素,如果元素不存在則拋出異常:
>> courses
{'C++', 'Vim', 'Linx', 'linux'}
>> courses.add('python')
>> 'python' in courses
True
>> courses
{'C++', 'Vim', 'Linx', 'linux', 'python'}
>> courses.remove('python')
>> 'python' in courses
False
>> courses
{'C++', 'Vim', 'Linx', 'linux'}
>> courses.remove('python')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'python'
集合運算符:
>> set1 = {1,2,3,4}
>> set2 = {3,4,5,6}
‘|’操作,存在set1中或者set2中的元素,等效於union:
>> set1 | set2
{1, 2, 3, 4, 5, 6}
>> set2.union(set1)
{1, 2, 3, 4, 5, 6}
'&'操作,返回即在set1又在set2的元素:
>> set1 & set2
{3, 4}
‘-’操作,返回在set1不在set2的元素:
>> set1 - set2
{1, 2}
‘^’操作,返回只存在兩個集合中無交集的元素:
>> set1 ^ set2
{1, 2, 5, 6}