创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典
集合相比于其他迭代序列,可以实现‘+’(左右差集),‘-’,并,交四个特殊功能
(1)set.add()
给集合添加元素
fruits = {"apple", "banana", "cherry"}
fruits.add('orange')
>>>{'cherry', 'orange', 'apple', 'banana'}
(2)set.clear()
移除集合所有元素
(3)set.copy()
拷贝一个集合
(4)set.difference()
返回两个集合的差集,即元素在第一个集合,但不包含在第二个集合中
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
z = x.difference(y)
>>>{'apple', 'banana'}
(5)set.difference_update()
与difference()作用相同,唯一的区别是没有返回值,直接在原集合本身进行修改。
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
x.difference_update(y)
>>>{'banana', 'apple'}
(6)set.intersection()
返回两个集合的交集,即元素在第一个集合,也包含在第二个集合中
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
z = x.intersection(y)
>>>{'cherry'}
(7)set.intersection_update()
与intersection()作用相同,唯一的区别是没有返回值,直接在原集合本身进行修改
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
x.intersection_update(y)
>>>{'cherry'}
(8)set.symmetric_difference()
返回一个包含两个集合中不重复元素的新集合
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
z = x.symmetric_difference(y)
>>>{'apple', 'orange', 'banana'}
(9)set.symmetric_difference_update()
与symmetric_difference()作用相同,唯一的区别是没有返回值,直接在原集合本身进行修改
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
x.symmetric_difference_update(y)
>>>{'orange', 'banana', 'apple'}
(10)set.union()
返回两个集合的并集
x = {"apple", "banana", "cherry"}
y = {"orange", "cherry"}
z = x.union(y)
>>>{'orange', 'banana', 'apple', 'cherry'}
(11)set.issubset()
判断集合是否是参数集合的子集
x = {"apple", "banana", "cherry"}
y = {"cherry"}
print(y.issubset(x))
>>>True
(12)set.issuperset()
判断集合是否是参数集合的父集
x = {"apple", "banana", "cherry"}
y = {"cherry"}
print(x.issuperset(y))
>>>True
(13)set.pop()
移除随机元素
x = {"apple", "banana", "cherry"}
x.pop()
>>>{'banana', 'cherry'}
(14)set.remove()
移除指定元素
x = {"apple", "banana", "cherry"}
x.remove('banana')
>>>{'apple', 'cherry'}
(15)set.isdisjoint()
判断两个集合是否包含相同元素,如果不包含则返回True。
x = {"apple", "banana", "cherry"}
y = {"cherry"}
z = x.isdisjoint(y)
>>>False