Python3学习笔记(八):集合

集合(set)是一种可变的无序的不重复的数据类型

要创建集合,需要将所有项(元素)放在花括号({})内,以逗号(,)分隔。

>>> s = {'p','y','t','h','o','n'}

集合中的元素必须是不可变的数据类型(数字,元组,字符串),不能是可变的数据类型(列表,字典,set集合)

>>> s = {1,2,3}           
>>> s = {1,'python',(1,2,3)}      # 元素可以为数字,字符串,元组    
>>> s = {1,2,[3,4]}               # 元素不能为列表
Traceback (most recent call last):
  File "<pyshell#208>", line 1, in <module>
    s = {1,2,[3,4]}
TypeError: unhashable type: 'list'
>>> s = {1,2,{'a':3,'b':4}}       # 元素不能为字典
Traceback (most recent call last):
  File "<pyshell#209>", line 1, in <module>
    s = {1,2,{'a':3,'b':4}}
TypeError: unhashable type: 'dict'

set()函数

用于把其他序列(字符串,列表,元组,字典)创建为集合

>>> set('python')        # 把字符串转变为集合   
{'o', 'h', 'p', 'n', 't', 'y'}
>>> set([1,2,3,4,5])    # 把列表转变为集合       
{1, 2, 3, 4, 5}
>>> set((1,2,3,4,5))    # 把元组转变为集合       
{1, 2, 3, 4, 5}
>>> set({'a':3,'b':4})  # 把字典键值转变为集合       
{'b', 'a'}
>>> set()               # 创建一个空集合
set()

集合特性

  • 无序性:元素之间是无序的,所以不支持索引。
  • 互异性:集合中每个元素都是不同的。
  • 确定性:给定一个集合,任给一个元素,该元素或者属于或者不属于该集合,二者必居其一,不允许有模棱两可的情况出现。
# 无序性
>>> s = set('python')           
>>> s           
{'o', 'h', 'p', 'n', 't', 'y'}
# 不支持索引
>>> s[2]           
Traceback (most recent call last):
  File "<pyshell#231>", line 1, in <module>
    s[2]
TypeError: 'set' object does not support indexing
# 互异性
>>> s = set('Hello')           
>>> s           
{'e', 'H', 'o', 'l'}
# 确定性
>>> 'l' in s           
True
>>> 'p' in s           
False

集合运算


集合之间可以进行并集、交集、差集运算

1、并集

一组集合的并集是这些集合的所有元素构成的集合,而不包含其他元素。

使用操作符 | 执行并集操作,同样地,也可使用方法 union() 完成。

>>> a = set('abcd')           
>>> b = set('cdef')           
>>> a | b           
{'d', 'e', 'b', 'c', 'f', 'a'}
>>> a.union(b)           
{'d', 'e', 'b', 'c', 'f', 'a'}

2、交集

两个集合 A 和 B 的交集是含有所有既属于 A 又属于 B 的元素,而没有其他元素的集合。

使用 & 操作符执行交集操作,同样地,也可使用方法 intersection() 完成

>>> a = set('abcd')           
>>> b = set('cdef')
>>> a & b           
{'d', 'c'}
>>> a.intersection(b)           
{'d', 'c'}

3、差集

A 与 B 的差集是所有属于 A 且不属于 B 的元素构成的集合

使用操作符 - 执行差集操作,同样地,也可使用方法 difference() 完成。

>>> a = set('abcd')           
>>> b = set('cdef')
>>> a - b           
{'a', 'b'}
>>> a.difference(b)           
{'a', 'b'}

猜你喜欢

转载自www.cnblogs.com/eastonliu/p/9097496.html
今日推荐