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.
Python 也有对应于集合的数据类型. 集合代表一群没有特定排列次序, 且并不重覆的元素. 合可以应用到会员身份验证, 或是剔除重覆项目上. 集合类也可以作数学上的 union, intersection, difference, symmetric difference 操作.
Here is a brief demonstration:
以下为简单示范:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruits = set(basket) # create a set without duplicates >>> fruits set(['orange', 'pear', 'apple', 'banana']) >>> 'orange' in fruits # fast membership testing True >>> 'crabgrass' in fruits 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'])