標籤:
python的set和其他語言類似, 是一個無序不重複元素集, 準系統包括關係測試和消除重複元素. 集合對象還支援union(聯合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數學運算.
下面來點簡單的小例子說明把。 >>> 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中,使用相應的最佳化函數可以大大的提高系統的運行效率。比如下面的這個例子:fromtime importtimelista=[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.365000009537set 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) # unionengineering_management = list(engineers & managers) # intersectionfulltime_management = list(managers - engineers - programmers) # differenceprint"employees", employeesprint"engineering_management" ,engineering_managementprint "fulltime_management", fulltime_management 輸出為:employees [‘Jack‘, ‘Sam‘, ‘Susan‘, ‘Jane‘, ‘Janice‘, ‘John‘, ‘Zack‘]engineering_management [‘Jane‘, ‘Jack‘]fulltime_management [‘Zack‘]
python 集合set