集合set
集合与之前列表、元组类似,可以存储多个数据,但是这些数据是不重复的
集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric_difference(对称差集)等数学运算.
#set无序不可重复的集合
x=set('abcd')
print('----------x--------------')
print(x)
print(type(x))
y=set(['h','e','l','l','o','s'])
print('-----------y-------------')
print(y)
z=set('spam')
print('-----------z-------------')
print(z)
print('---------y&z交集---------------')
#y&z交集
print(y&z)
print('----------x|y并集--------------')
#x|y并集
print(x|y)
print('----------x-y 差集--------------')
#x-y 差集
print(x-y)
print('----------x^z对称差集(在x或z中,但不会同时出现在二者中)--------------')
#x^z对称差集(在x或z中,但不会同时出现在二者中)
print(x^z)
print('-----------集合x,y,z长度--------------')
print(len(x))
print(len(y))
print(len(z))
运行结果:
----------x-------------- {'c', 'a', 'd', 'b'} <class 'set'> -----------y------------- {'l', 'o', 's', 'h', 'e'} -----------z------------- {'s', 'm', 'a', 'p'} ---------y&z交集--------------- {'s'} ----------x|y并集-------------- {'l', 'h', 'd', 'c', 'e', 's', 'o', 'a', 'b'} ----------x-y 差集-------------- {'b', 'a', 'd', 'c'} ----------x^z对称差集(在x或z中,但不会同时出现在二者中)-------------- {'p', 'd', 'c', 's', 'm', 'b'} -----------集合x,y,z长度-------------- 4 5 4
浙公网安备 33010602011771号