首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

Python - Sets

2012-08-31 
Python ---- SetsPython also includes a data type for sets. A set is an unordered collection with no

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'])

热点排行