python的set和其他語言類似, 是一個無序不重復元素集, 基本功能包括關系測試和消除重復元素. 集合對象還支持union(聯(lián)合), intersection(交), difference(差)和sysmmetric difference(對稱差集)等數(shù)學運算.
>>> basket = [’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’]
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set([’orange’, ’pear’, ’apple’, ’banana’])
>>> ’orange’ in fruit # fast membership testing
True
>>> ’crabgrass’ in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set(’abracadabra’)
>>> b = set(’alacazam’)
>>> a # unique letters in a
set([’a’, ’r’, ’b’, ’c’, ’d’])
>>> a - b # letters in a but not in b
set([’r’, ’d’, ’b’])
>>> a | b # letters in either a or b
set([’a’, ’c’, ’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
>>> a & b # letters in both a and b
set([’a’, ’c’])
>>> a ^ b # letters in a or b but not both
set([’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
posted on 2009-06-02 21:24
周銳 閱讀(1023)
評論(0) 編輯 收藏 所屬分類:
Python