一:集合的定义和基本操作 集合是一个无序的,不重复的数据组合,它的主要作用如下: - 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
集合用set来表示。
第一段代码:
- s = set([3, 5, 9, 10]) # 创建一个数值集合
- t = set("Hello") # 创建一个唯一字符的集合
- print("s is :",s)
- print("t is :",t)
- a = t | s # t 和 s的并集
- print("a is :",a)
- b = t & s # t 和 s的交集
- print("b is :",b)
- c = t - s # 求差集(项在t中,但不在s中)
- print("c is :",c)
- d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中)
- print("d is :",d)
复制代码 输出:- s is : {9, 10, 3, 5}
- t is : {'l', 'e', 'H', 'o'}
- a is : {3, 'H', 'o', 5, 9, 10, 'l', 'e'}
- b is : set()
- c is : {'l', 'e', 'H', 'o'}
- d is : {3, 'H', 5, 'o', 9, 10, 'l', 'e'}
复制代码
第二段代码(有重复数字、且不是唯一字符)代码:- s = set([3, 5, 9, 10,11,5,10]) # 创建一个数值集合
- t = set(["Hello","Beijing"])
- print("s is :",s)
- print("t is :",t)
- a = t | s # t 和 s的并集
- print("a is :",a)
- b = t & s # t 和 s的交集
- print("b is :",b)
- c = t - s # 求差集(项在t中,但不在s中)
- print("c is :",c)
- d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中)
- print("d is :",d)
复制代码 输出:- s is : {11, 9, 10, 3, 5}
- t is : {'Hello', 'Beijing'}
- a is : {10, 3, 5, 'Beijing', 9, 'Hello', 11}
- b is : set()
- c is : {'Hello', 'Beijing'}
- d is : {3, 5, 9, 10, 11, 'Beijing', 'Hello'}
复制代码 第三段代码(都是数字的集合)
代码:- s = set([3, 5, 9, 10,11,5,10]) # 创建一个数值集合
- t = set([4,5,6,7,8,9])
- print("s is :",s)
- print("t is :",t)
- a = t | s # t 和 s的并集
- print("a is :",a)
- b = t & s # t 和 s的交集
- print("b is :",b)
- c = t - s # 求差集(项在t中,但不在s中)
- print("c is :",c)
- d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中)
- print("d is :",d)
复制代码 输出:- s is : {11, 9, 10, 3, 5}
- t is : {4, 5, 6, 7, 8, 9}
- a is : {3, 4, 5, 6, 7, 8, 9, 10, 11}
- b is : {9, 5}
- c is : {8, 4, 6, 7}
- d is : {3, 4, 6, 7, 8, 10, 11}
复制代码 |