集合类型
集合类型
1.什么是集合:一个集合里有一组数据
# 大括号内用逗号隔开多个元素,集合(哈希表)是无序的,去重
s1 = {'nick','handsome','wuhao','dsb',1231,1.0,1.0,1.0,'dsb','dsb'}
print(s1) # {1.0, 'dsb', 'nick', 1231, 'handsome', 'wuhao'}
s2 = set('nick') # iterable(序列类型)
s3 = set(['1',2,3])
print(s2) # {'k', 'i', 'n', 'c'}
print(s3) # {2, 3, '1'}
name1 = 'nick'
name2 = str('nick')
print('name1:',name1) # name1: nick
print('name2:',name2) # name2: nick
2.集合和集合之间会有:交集&,并集|,补集^,差集-
s1 = {'piao','wuhao','dsb'}
s2 = {'piao','yongjiu','sb'}
print(s1 & s2) # {'piao'}
print(s1 | s2) # {'wuhao', 'yongjiu', 'piao', 'sb', 'dsb'}
print(s1 ^ s2) # {'wuhao', 'yongjiu', 'sb', 'dsb'}
print(s1 - s2) # {'wuhao', 'dsb'}
print('*' * 50)
3.集合的内置方法
s1 = {'nick','handsome','wuhao','dsb',1231,1.0,1.0,1.0,'dsb','dsb'}
s1.add('wuhao dsb')
print(s1) # {1.0, 'wuhao dsb', 1231, 'nick', 'wuhao', 'dsb', 'handsome'}
# 丢掉的是没有的则报错
s1.remove(1.0)
print(s1) # {'handsome', 1231, 'nick', 'wuhao dsb', 'wuhao', 'dsb'}
# 丢掉的是没有的不报错
s1.discard(3)
print(s1) # {'nick', 'handsome', 1231, 'dsb', 'wuhao', 'wuhao dsb'}
# 清空
# s1.clear()
# print(s1) # set()
# 复制
s2 = s1.copy()
print("s2:",s2) # s2: {'nick', 'wuhao dsb', 'dsb', 'handsome', 'wuhao', 1231}