-
定义
set----->{}
无序不重复
空集合: set1 = set(),集合set2 = {1,2,3} -
集合中的方法
''' len(set1) for i in set1 in,not in set1.add(x):添加元素x,将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。 set1.update(x,y,z):添加元素x,可以是多个,可以是list,tuple,dict set1.remove( x ):将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。 set1.discard( x ):移除集合中的元素,且如果元素不存在,不会发生错误。 set1.pop():随机删除集合中的一个元素 add() 为集合添加元素 clear() 移除集合中的所有元素 copy() 拷贝一个集合 difference() 返回多个集合的差集 difference_update() 移除集合中的元素,该元素在指定的集合也存在。 discard() 删除集合中指定的元素 intersection() 返回集合的交集 intersection_update() 删除集合中的元素,该元素在指定的集合中不存在。 isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 issubset() 判断指定集合是否为该方法参数集合的子集。 issuperset() 判断该方法的参数集合是否为指定集合的子集 pop() 随机移除元素 remove() 移除指定元素 symmetric_difference() 返回两个集合中不重复的元素集合。 symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 union 返回两个集合的并集 update() 给集合添加元素 更新: 两个集合的: 交集: & set1 & set2 ---> 共同存在元素 并集: | set1 | set2 ---> 差集: - set1 - set2 ---> 找set1与set2不一样的元素 对称差集: ^ set1 ^ set2 ----> '''
-
练习
# s1 = {1, 2, 3, 4} # s2 = {3, 4, 5, 6} # print(s1.difference(s2)) # s1.difference_update(s2) # print(s1) # print(s1.intersection(s2)) # s1.intersection_update(s2) # print(s1) # print(s1.symmetric_difference(s2)) # print(s1) # s1.symmetric_difference_update(s2) # print(s1) # import random # set1 = {9, 3.5, 21, 34, 43, 3, 3, 3} # print(set1) # set1 = set() # i = 0 # while i < 8: # # 产生随机数 # ran = random.randint(0, i+2) # if ran in set1: # continue # else: # set1.add(ran) # i += 1 # # print(set1) # set1 = {'aa', 'bb', 'cc'} # tuple1 = ('dd', 'ee') # set1.update(tuple1) # print(set1) # 练习: 定义空集合,1. 添加几个人名,键盘输入要查找的人名, # 如果能够查到打印这个人名,否则显示没有找到 # 3. 随机删除里面的2个人名 # set1 = set() # set2 = {'aa', 'ss', 'dd', 'ff', 'gg'} # set1.update(set2) # print(set1) # x = input('输入:') # if x in set1: # print(x) # else: # print('没有') # set1.pop() # set1.pop() # print(set1) # 玩家A: 可以循环要5张1-10之间不同的牌,玩家B也可以要5张1-10之间不同的牌 # 1.找出双方都存在的牌 # 2.找出A有B不存在的牌 # 3.判断输赢,谁的不同的点数和大,谁赢 # print('------SB游戏------') # while True: # set1 = set() # set2 = set() # i = 0 # while i < 5: # # 产生随机数 # ran = random.randint(1, 10) # if ran in set1: # continue # else: # set1.add(ran) # i += 1 # j = 0 # while j < 5: # # 产生随机数 # ran = random.randint(1, 10) # if ran in set2: # continue # else: # set2.add(ran) # j += 1 # set3 = set1 & set2 # print(set1) # print(set2) # print(set3) # print(set1 - set3) # print(set2 - set3) # if sum(set1 - set3) > sum(set2 - set3): # print('A赢了') # else: # print('B赢了') # x = input('继续1,结束2:') # if x == '2': # break
集合————set
最新推荐文章于 2022-04-16 14:23:39 发布