9、检查一个集合是否是另一个集合的子集
【1】使用<=
【2】使用issubset
setx = set(["apple", "mango"]) sety = set(["mango", "orange"]) setz = set(["mango"]) print("If x is subset of y:") print(setx <= sety) print(setx.issubset(sety)) print("If y is subset of x:") print(sety <= setx) print(sety.issubset(setx)) print("\nIf y is subset of z:") print(sety <= setz) print(sety.issubset(setz)) print("If z is subset of y:") print(setz <= sety) print(setz.issubset(sety)) ''' If x is subset of y: False False If y is subset of x: False False If y is subset of z: False False If z is subset of y: True True '''
10、从给定的集合中删除所有元素
编写一个Python程序以从给定的集合中删除所有元素。
setc = {"Red", "Green", "Black", "White"} setc.clear() print(setc) # set()
11、在一个集合中查找最大值和最小值
#Create a set setn = {5, 10, 3, 15, 2, 20} print("Original set elements:") print(setn) print(type(setn)) print("\nMaximum value of the said set:") print(max(setn)) print("\nMinimum value of the said set:") print(min(setn)) ''' Original set elements: {2, 3, 20, 5, 10, 15} <class 'set'> Maximum value of the said set: 20 Minimum value of the said set: 2 '''
12、查找集合的长度
编写一个 Python 程序来查找集合的长度。
#Create a set setn = {5, 10, 3, 15, 2, 20} print("Original set elements:") print(setn) print(type(setn)) print("Length of the said set:") print(len(setn)) setn = {5, 5, 5, 5, 5, 5} print("\nOriginal set elements:") print(setn) print(type(setn)) print("Length of the said set:") print(len(setn)) ''' Original set elements: {2, 3, 20, 5, 10, 15} <class 'set'> Length of the said set: 6 Original set elements: {5} <class 'set'> Length of the said set: 1 '''
13、检查给定值是否存在于集合中
使用in
和not in
nums = {1, 3, 5, 7, 9, 11} print("Test if 7 exists in nums:") print(7 in nums) print("Test if 6 is not in nums") print(6 not in nums) ''' Test if 7 exists in nums: True Test if 6 is not in nums True '''
14、检查两个给定的集合是否没有共同的元素
【1】isdisjoint
isdisjoint的功能
判断两个集合是否包含相同的元素,如果没有返回True,否则返回False
isdisjoint的用法
【1】语法:a_set.isdisjoint(b_set)
【2】参数:b_set:与当前集合用来判断的集合
【3】返回值:返回一个布尔值True或False
x = {1,2,3,4} y = {4,5,6,7} z = {8} print("\nConfirm two given sets have no element(s) in common:") print("\nCompare x and y:") print(x.isdisjoint(y)) print("\nCompare x and z:") print(z.isdisjoint(x)) print("\nCompare y and z:") print(y.isdisjoint(z)) ''' Confirm two given sets have no element(s) in common: Compare x and y: False Compare x and z: True Compare y and z: True '''
15、从第一组中删除第二组的交集
【2】difference_update
difference_update() 方法用于移除两个集合中都存在的元素。
difference_update() 方法与 difference() 方法的区别在于 difference() 方法返回一个移除相同元素的新集合,而 difference_update() 方法是直接在原来的集合中移除元素,没有返回值。
difference()移除元素后,需要一个新的“容器”去“承载”返回值。而difference_update() 是对集合的直接修改。
sn1 = {1,2,3,4,5} sn2 = {4,5,6,7,8} print("\nsn1中移除相同的元素,sn2不变") sn1.difference_update(sn2) print("sn1: ",sn1) print("sn2: ",sn2) ''' sn1中移除相同的元素,sn2不变 sn1: {1, 2, 3} sn2: {4, 5, 6, 7, 8} '''