Python基础 - 集合 Set

2018-05-21  本文已影响94人  彼岸的渔夫
人生苦短,我用Python:花了一生学Python

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

set对象是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(并), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.

Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

sets支持x in set, len(set),和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入顺序。因此,sets不支持 indexing(索引), slicing(切片), 或其它类序列(sequence-like)的操作。

有两种内置set类型:set and frozensetset 类型是可变的,frozenset类型是不可变的。

创建集合

>>> s = {'a','b','c','d'}
>>> s
{'a', 'd', 'b', 'c'}
>>> type(s)
<class 'set'>

>>> s2 = {['a','b','c','d']}    #  列表
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    s2 = {['a','b','c','d']}
TypeError: unhashable type: 'list'

>>> s3 = {('a','b','c','d')}   #  元组
>>> s3
{('a', 'b', 'c', 'd')}
>>> type(s3)
<class 'set'>

>>> s = set()    #注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典
>>> s
set()
>>> s = set([2,3,4,5,6])
>>> s
{2, 3, 4, 5, 6}

''' set() 函数'''
>>> a = set('hello')
>>> b = set('boy')
>>> c = set({'k1':'v1','k2':'v2'})
>>> a
{'h', 'e', 'l', 'o'}
>>> b
{'y', 'b', 'o'}
>>> c
{'k1', 'k2'}
>>> a,b,c
({'h', 'e', 'l', 'o'}, {'y', 'b', 'o'}, {'k1', 'k2'})

集合的基本操作

以下方法对setfrozenset均适用:

注:非操作符的方法union(), intersection(), difference(),和 issubset()
issuperset()symmetric_difference()接受任何可迭代对象作为参数 。

以下方法适用于可变的set,但不适用于不可变的frozenset:

>>> s = {'a','b','c','d'}
>>> t = {'a','11','22'}
>>> s.update(t)
>>> s
{'22', 'b', 'a', 'd', '11', 'c'}
>>> s = {'a','b','c','d'}
>>> s.add('e')
>>> s
{'a', 'e', 'c', 'b', 'd'}
>>> s = {'a','b','c','d'}
>>> s.remove('a')
>>> s
{'d', 'b', 'c'}
>>> s.remove('e')
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    s.remove('e')
KeyError: 'e'
>>> s = {'a','b','c','d'}
>>> s.discard('a')
>>> s
{'d', 'b', 'c'}
>>> s.discard('e')   # 移除不存的元素不会报错
>>> s
{'d', 'b', 'c'}
>>> s = {'a','b','c','d'}
>>> s.pop()
'a'
>>> s.pop()
'd'
>>> s
{'b', 'c'}
>>> s.clear()
>>> s.pop()  
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    s.pop()
KeyError: 'pop from an empty set'
>>> s = {'a','b','c','d'}
>>> s.clear()
>>> s
set()

注:非操作符的方法update(), intersection_update(), difference_update()symmetric_difference_update() 接受任何可迭代对象作为参数。

上一篇下一篇

猜你喜欢

热点阅读