python 集合set

來源:互聯網
上載者:User

標籤:

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.