python基础数据类型--集合(set)

python基础数据类型--集合(set)

集合是一个数学概念由一个或多个确定的元素所构成的整体叫做集合

集合中的三个特征

1.确定性(元素必须死可hash)

2.互异性(去重)

3.无序性(集合中的元素没有先后之分)如集合{1,2,3}和集合{2,3,1}算作一个集合

 

注意  集合存在的意义就是去重和关系运算

 

一、集合的创建

set1 = {1,2,3}

set2 = set({1,2,3})

单个元素的增加add(),     add的作用相当于列表中的append

序列的增加:update(),    update类似于extend方法,update方法可以支持同时传入多个参数

a = {1,2}
a.update([3,4],[1,2,7])   #迭代加  去重
>>>>a
{1, 2, 3, 4, 7}

a.update('hello')    #迭代加
>>>>a
{1, 2, 3, 4, 7, 'h', 'o', 'e', 'l'}

a.add('hello')      #追加
>>>a
{1, 2, 3, 4, 7, 'h', 'o', 'hello', 'e', 'l'}

  

删除

集合删除单个元素有两种方法:

元素不在原集合里

set.discard(x)  不会抛出异常

set.remove(x)  会抛出keyError错误

 

a = {1,2,3,4}

a.discard(1)
print(a)
a.discard(1)   #不会报错
print(a)
a.remove(1)   #报错
print(a)


>>>>

{2, 3, 4}
{2, 3, 4}
Traceback (most recent call last):
  File "D:/untitled/假期/2018-2-9/基础知识五--集合.py", line 19, in <module>
    a.remove(1)
KeyError: 1

pop():由于集合是无序的,pop返回的结果不能确定,且当集合为空时调用pop会抛出KeyError错误,

clear(): 清空集合

 

a = {3,'a',2.1,1}
a.pop()
a.pop()    #删除是无序的
a.clear()  #清空 
print(a)
a.pop()    #报错
print(a)



>>>>
set()
Traceback (most recent call last):
  File "D:/untitled/假期/2018-2-9/基础知识五--集合.py", line 28, in <module>
    a.pop()
KeyError: 'pop from an empty set'

 

查  

只能用for循环

for i in set1:
    print(i)

集合的运算

# ①交集
set1 = {'a', 'b', 'c', 'd', '1', '4'}
set2 = {'1', '2', '3', '4', 'b', 'c'}
print(set1 & set2)
>>> {'c', '4', '1', 'b'}
print(set1.intersection(set2))
>>> {'c', '4', '1', 'b'}

# ②反交集
set1 = {'a', 'b', 'c', 'd', '1', '4'}
set2 = {'1', '2', '3', '4', 'b', 'c'}
print(set1 ^ set2)
>>> {'d', '2', 'a', '3'}
print(set1.symmetric_difference(set2))
>>> {'d', '2', 'a', '3'}

# ③并集
set1 = {'a', 'b', 'c', 'd', '1', '4'}
set2 = {'1', '2', '3', '4', 'b', 'c'}
print(set1 | set2)
>>> {'1', 'b', '2', '3', 'c', 'd', '4', 'a'}
print(set1.union(set2))
>>> {'1', 'b', '2', '3', 'c', 'd', '4', 'a'}

# ④差集
set1 = {'a', 'b', 'c', 'd', '1', '4'}
set2 = {'1', '2', '3', '4', 'b', 'c'}
print(set1 - set2)
>>> {'d', 'a'}
print(set1.difference(set2))
>>> {'d', 'a'}

print(set2 - set1)
>>> {'2', '3'}
print(set2.difference(set1))
>>> {'2', '3'}

# ⑤子集与超集
set1 = {'A','B','C','a','b','c'}
set2 = {'A','B','C'}
print(set2 < set1)
>>> True
print(set2.issubset(set1))
>>> True

print(set1 > set2)
>>> True
print(set1.issuperset(set2))
>>> True

不可变集合

# 不可变集合
set_frozen = frozenset({'A', 'B', 'C'})
print(set_frozen)
>>> frozenset({'C', 'B', 'A'})

 

posted @ 2018-02-23 23:22  流年中渲染了微笑  阅读(296)  评论(0编辑  收藏  举报