读书人

Python - Sets

发布时间: 2012-08-31 12:55:03 作者: rapoo

Python ---- Sets
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Here is a brief demonstration:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> fruit = set(basket)               # create a set without duplicates>>> fruitset(['orange', 'pear', 'apple', 'banana'])>>> 'orange' in fruit                 # fast membership testingTrue>>> 'crabgrass' in fruitFalse>>> # Demonstrate set operations on unique letters from two words...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a                                  # unique letters in aset(['a', 'r', 'b', 'c', 'd'])>>> a - b                              # letters in a but not in bset(['r', 'd', 'b'])>>> a | b                              # letters in either a or bset(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])>>> a & b                              # letters in both a and bset(['a', 'c'])>>> a ^ b                              # letters in a or b but not bothset(['r', 'd', 'b', 'm', 'z', 'l'])

读书人网 >perl python

热点推荐