1.
集合(set):把不同的元素组成一起形成集合,是python基本的数据类型。
集合对象是一组无序排列hashable value:集合成员可以做字典的键。
集合就像是 list 和 dict 的组合。
#coding:utf8
a=['h','e','l','l','o']
a=set(a)
b=set('welcome')
print " a = " ,a
print " b = " ,b
print " 并集 ",a.union(b) #a|b #并集
print " 并集 ",a|b #并集
print '*'*30
print " 交集 ",a.intersection(b) #交集
print " 交集 ",a&b #交集
print '*'*30
print " 差集 ",b-a #差集
print " 差集 ",b.difference(a) #差集
print " 差集 ",a-b
print '*'*30
print " 对称差集 ",a^b #对称差集
print " 对称差集 ",a.symmetric_difference(b) #对称差集
'''
a = set(['h', 'e', 'l', 'o'])
b = set(['c', 'e', 'm', 'l', 'o', 'w'])
并集 set(['c', 'e', 'h', 'm', 'l', 'o', 'w'])
并集 set(['c', 'e', 'h', 'm', 'l', 'o', 'w'])
******************************
交集 set(['e', 'l', 'o'])
交集 set(['e', 'l', 'o'])
******************************
差集 set(['c', 'm', 'w'])
差集 set(['c', 'm', 'w'])
差集 set(['h'])
******************************
对称差集 set(['c', 'w', 'h', 'm'])
对称差集 set(['c', 'w', 'h', 'm'])
'''
2.添加 删除 set
#coding:utf8
a=set('hello')
print a
a=set('hello')
a.update("asdf")
print 'a.update("asdf") ',a
a=set('hello')
a.add("asdf")
print 'a.add("asdf") ',a
a.pop() #随机删除了一个
print a
a.discard('p')#当集合中没有这个元素的时候,不会报错
a.remove('t') #当集合中没有这个元素的时候报错
'''
set(['h', 'e', 'l', 'o'])
a.update("asdf") set(['a', 'e', 'd', 'f', 'h', 'l', 'o', 's'])
a.add("asdf") set(['h', 'asdf', 'e', 'l', 'o'])
set(['asdf', 'e', 'l', 'o'])
a.remove('t') #当集合中没有这个元素的时候报错
Traceback (most recent call last):
File "D:\AlamTW\study\python\20170711.py", line 20, in <module>
KeyError: 't'
'''