print(student) #显示集合以及去重功能
#判断 Tom 是否在集合中
if( 'Tom'instudent) :
print( 'true')
else:
print( 'false')
#集合间的运算
#创建集合
a = set( 'abcd')
b = set( 'abc')
#输出集合
print(a)
print(a-b) #a b的差集
print(a|b) #a b的并集
print(a&b) #a b的交集
print(a^b) #a b中不同时存在的元素
结果如下
{ 'Jim', 'Jack', 'Tom', 'Mary'}
true
{ 'b', 'd', 'a', 'c'}
{ 'd'}
{ 'd', 'a', 'b', 'c'}
{ 'b', 'a', 'c'}
{ 'd'}
集合的基本操作
1. 添加元素
语法格式如下:
s.add( x )
将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。
代码实例
>>>thisset = set(( "Google", "Baidu", "Taobao"))
>>>thisset.add( "Facebook")
>>>print(thisset)
{ 'Facebook', 'Google', 'Baidu', 'Taobao'}
>>>
还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:
s.update( x )
x 可以有多个,用逗号分开。
代码实例
>>>thisset = set(( "Google", "Baidu", "Taobao"))
>>>thisset.update({ 1, 3})
>>>print(thisset)
{ 1, 3, 'Google', 'Taobao', 'Baidu'}
>>>thisset.update([ 1, 4],[ 5, 6])
>>>print(thisset)
{ 1, 3, 4, 5, 6, 'Google', 'Taobao', 'Baidu'}
>>>
2. 移除元素
语法格式如下:
s.remove( x )
将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。
>>>thisset = set(( "Google", "Baidu", "Taobao"))
>>>thisset.remove( "Taobao")
>>>print(thisset)
{ 'Google', 'Baidu'}
>>>thisset.remove( "Facebook") # 不存在会发生错误
Traceback (most recent call last):
File "", line 1, in
KeyError: 'Facebook'
>>>
此外还有一个方法也是移除集合中的元素,且如果元素不存在, 不会发生错误。格式如下所示:
s.discard( x )
代码实例
>>>thisset = set(( "Google", "Baidu", "Taobao"))
>>>thisset.discard( "Facebook") # 不存在不会发生错误
>>>print(thisset)
{ 'Taobao', 'Google', 'Baidu'}
也可以设置随机删除集合中的一个元素,语法格式如下:
s.pop
thisset = set(( "Google", "Baidu", "Taobao", "Facebook"))
x = thisset.pop
print(x)
==================结果================
>>>
set 集合的 pop 方法会对集合进行无序的排列,然后将这个无序排列集合的左面第一个元素进行删除。
3. 清空集合
语法格式如下:
s.clear
代码实例
>>>thisset = set(( "Google", "Baidu", "Taobao"))
>>>thisset.clear
>>>print(thisset)
set
4. 计算集合元素个数
语法格式如下:
len(s)
计算集合 s 元素个数。
>>>thisset = set(( "Google", "Baidu", "Taobao"))
>>>len(thisset)
3