天天看點

Python之路--集合Python 集合集合的基本操作

Python 集合

集合(set)是一個無序不重複元素的序列。

可以使用大括号 { } 或者 set() 函數建立集合,注意:建立一個空集合必須用 set() 而不是 { },因為 { } 是用來建立一個空字典。

建立格式:

parame = {value01,value02,...}
或者
set(value)
           

執行個體

>>> values = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(values)   # 這裡示範的是去重功能
{'apple', 'pear', 'orange', 'banana'}
>>> 'banana' in values     # 快速判斷元素是否在集合内
True
>>> 'stealth' in values
False
>>>


# 下面展示兩個集合間的運算.

>>> a = set('abcdefgcd')
>>> b = set('abddgss')
>>> a
{'c', 'g', 'a', 'b', 'd', 'e', 'f'}
>>> b
{'g', 'a', 'b', 'd', 's'}

>>> a - b     # 集合a中包含元素
{'e', 'f', 'c'}

>>> a | b    # 集合a或b中包含的所有元素
{'c', 'g', 'a', 'b', 'd', 'e', 'f', 's'}

>>> a & b    # 集合a和b中都包含了的元素
{'d', 'a', 'g', 'b'}

>>> a ^ b   # 不同時包含于a和b的元素
{'c', 'e', 'f', 's'}
>>>
           

集合的基本操作

1、添加元素

文法格式如下:

s.add( x )      

将元素 x 添加到集合 s 中,如果元素已存在,則不進行任何操作。

執行個體

>>> thisset = set(('google','runoob','taobao'))
>>> thisset.add('facebook')
>>> print(thisset)
{'facebook', 'google', 'runoob', 'taobao'}
>>>
           

還有一個方法,也可以添加元素,且參數可以是清單,元組,字典等,文法格式如下:

s.update( x )      

x 可以有多個,用逗号分開。

執行個體

>>> thisset = set(('google','runoob','taobao'))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'taobao', 'google', 'runoob'}
>>> thisset.update([1,4],[5,6])
>>> print(thisset)
{1, 3, 'taobao', 4, 5, 6, 'google', 'runoob'}
>>>
           

2、移除元素

文法格式如下:

s.remove( x )      

将元素 x 添加到集合 s 中移除,如果元素不存在,則會發生錯誤。

執行個體

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Runoob'}
>>> thisset.remove("stealth")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'stealth'
>>>
           

此外還有一個方法也是移除集合中的元素,且如果元素不存在,不會發生錯誤。格式如下所示:

s.discard( x )      

執行個體

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.discard("stealth")
>>> print(thisset)
{'Google', 'Runoob', 'Taobao'}
>>>
           

我們也可以設定随機删除集合中的一個元素,文法格式如下:

s.pop()       

執行個體

>>> thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
>>> thisset.pop()
'Facebook'
>>> print(thisset)
{'Google', 'Runoob', 'Taobao'}
>>>
           

3、計算集合元素個數

文法格式如下:

len(s)      

計算集合 s 元素個數。

執行個體

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> len(thisset)
3
>>>
           

4、清空集合

文法格式如下:

s.clear()      

清空集合 s。

執行個體

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()
>>>
           

5、判斷元素是否在集合中存在

文法格式如下:

x in s      

判斷元素 s 是否在集合 x 中存在,存在傳回 True,不存在傳回 False。

執行個體

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> "Runoob" in thisset
True
>>> "steatl" in thisset
False
>>>
           

繼續閱讀