python的set和其餘語言相似, 是一個無序不重複元素集, 基本功能包括關係測試和消除重複元素. 集合對象還支持union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算. python
下面來點簡單的小例子說明把。 >>> x = set('spam') >>> y = set(['h','a','m']) >>> x, y (set(['a', 'p', 's', 'm']), set(['a', 'h', 'm'])) 再來些小應用。 >>> x & y # 交集 set(['a', 'm']) >>> x | y # 並集 set(['a', 'p', 's', 'h', 'm']) >>> x - y # 差集 set(['p', 's'])
a = t | s # t 和 s的並集 b = t & s # t 和 s的交集 c = t – s # 求差集(項在t中,但不在s中) d = t ^ s # 對稱差集(項在t或s中,但不會同時出如今兩者中)
#Python中,使用相應的優化函數能夠大大的提升系統的運行效率。好比下面的這個例子: from time import time lista=[1,2, 3, 4,5, 6, 7 ,8, 9, 10, 25, 50, 36, 43, 52] listb=[2, 4, 6, 9, 36] def noset_test(): t = time() filter=[] for i in range(100000): for a in lista: for b in listb: if a==b: filter.append(a) print 'no set total run time:' print time() -t def set_test(): t1 = time() for i in range(100000): list(set(lista)&set(listb)) print "set total run time:" print time() - t1 noset_test(); set_test(); 輸出爲: no set total run time: 0.365000009537 set total run time: 0.15700006485 經過使用set,運行的時間明顯的有縮減。
engineers = set(['John', 'Jane', 'Jack', 'Janice']) programmers = set(['Jack', 'Sam', 'Susan', 'Janice']) managers = set(['Jane', 'Jack', 'Susan', 'Zack']) employees = list(engineers | programmers | managers) # union engineering_management = list(engineers & managers) # intersection fulltime_management = list(managers - engineers - programmers) # difference print"employees", employees print"engineering_management" ,engineering_management print "fulltime_management", fulltime_management 輸出爲: employees ['Jack', 'Sam', 'Susan', 'Jane', 'Janice', 'John', 'Zack'] engineering_management ['Jane', 'Jack'] fulltime_management ['Zack']