什么是集合(set)
''' 集合是容器型数据类型,将{}作为容器的标志,里面多个元素用逗号隔开:{元素1, 元素2, 元素3, 元素4, 。。。。} 集合是可变的,无序的 元素: 不可变的,唯一的 ''' # 1) 空集合 x = {} # 空字典 s1 = set () # 空集合 print(type(x), type(s1)) # <class 'dict'> <class 'set'> print(s1) # set() # 2) 元素是不可变的 s2 = {10, 'abc', (1, 2)} print(s2) # {(1, 2), 'abc', 10} # 报错,列表可变不能作为集合元素 # s3 = {10, 'abc', [1, 2]} # TypeError: unhashable type: 'list' # 3) 元素是唯一的 s4 = {10, 20, 30, 40, 10, 10} print(s4) # {10, 20, 30, 40} # 集合去重 names = {'张三', '李四', '老王', '李四', '张三', '张三'} names == list(set(names)) print(names) nums = {2, 30, 4, 10, 10, 2, 50, 6, 30} nums = list(set(nums)) print(nums) # 4)集合是无序的 print({1, 3, 5} == {5, 1, 3}) # True # 2.集合的增删改查 # 1) 查 - 集合只能遍历 # 补充: 通过for循环遍历无序序列的时候,都是先将序列转换成列表,然后遍历列表 games = {'QQ炫舞', '扫雷', '贪吃蛇', '我的世界', '侠盗猎车', '红警'} for x in games: print('x:', x) # 2) 增 # 集合.add(元素) - 在集合中添加指定元素 # 集合.update(序列) - 将序列中所有的元素添加到集合中 games.add('英雄联盟') print(games) games.update({'开心消消乐', '王者荣耀'}) print(games) games.update('abc') print(games) # {'红警', '贪吃蛇', 'QQ炫舞', '英雄联盟', '王者荣耀', '扫雷', '侠盗猎车', '开心消消乐', 'a', 'c', 'b', '我的世界'} # 3) 删 # 集合.remove(元素) - 删除集合中指定的元素 # 集合.discard(元素) - 删除集合中指定的元素(元素不存在不会报错) # 4) 改 - 先删除原来的, 再添加新的 games = {'QQ炫舞', '扫雷', '贪吃蛇', '我的世界', '侠盗猎车', '红警'} games.remove('扫雷') games.add('部落冲突') # 3)数学集合运算 # python中的集合支持数学中的集合运算: &(交集)丶|(并集)、-(差集)、^(对称差集) set1 = {1, 2, 3, 4, 5, 6, 7} set2 = {4, 5, 6, 7, 8, 9, 10} # 2) 集合1 | 集合2 - 合并两个集合产生一个新的集合 print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} # 3) 集合1 - 集合2 - 集合1去掉包含在集合2中剩下的元素 print(set1 - set2) # {1, 2, 3} print(set2 - set1) # {8, 9, 10} # 4) 集合1 ^ 集合2 - 将两个集合合并后去掉公共部分 print(set1 ^ set2) # {1, 2, 3, 8, 9, 10} # 5) # 集合1 > 集合2 - 判断集合2是否是集合1的真子集 # 集合1 < 集合2 - 判断集合1是否是集合2的真子集 # 集合1 >= 集合2 - 判断集合2是否是集合1的子集 # 集合1 <= 集合2 - 判断集合1是否是集合2的子集 print({1, 2, 3, 4} > {1, 2}) # True print({1, 2, 3, 4} > {1, 2, 3, 4}) # False print({1, 2, 3, 4} >= {1, 2, 3, 4}) # True print({1, 2, 3, 4} >= {1, 2}) # True print({100, 200, 300} > {1, 2}) # False