Set set is characterized by unordered, non-repeating sequences
To create a collection:
| 12345678910111213 |
a.s1 = {11,22}b.s2 = set()c.s3 = set([11,22,33,44])s = set() #创建空集合li = [11,22,11,22]s2 = set(li)print(s2){11, 22}se = {"123","456"}li = [ ]list((11,22,33,44))原理:当执行list()时,内部会调用list __init__,内部执行for循环(11,22,33,44) [11,22,33,44]#只要类()这样的形式,就会去调用__init__的方法。 |
Operation Collection:
| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
s = set()s.add(123) #添加元素s.add(123)s.add(123)print(s) s.clear() #清空内容s.copy() #浅拷贝s1 = {11,22,33}s2 = {22,33,44}s3 = s1.difference(s2) #a中存在,b中不存在的 s1中存在,s2中不存在s4 = s2.difference(s1) #s2中存在,s1中不存在# s3 = s1.symmetric_difference(s2) #a中存在b中不存在,b中存在a中不存在的拿出来。# print(s3)# s1.difference_update(s2) #把a(s1)中存在,b(s2)中不存在的值更新到a中。如果以后还会用到s1,就不要用此方法,如果确定以后不会再用# s1了就可以直接用这个方法。这样的好处是减少变量的声明。# print(s1)# s1.discard(11) #移除指定元素,如果元素不存在则不报错# s1.remove(1111) #移除指定元素,如果元素不存在则报错# s1.pop() #随机移除一个s1中的元素,因为集合是无序的,所以移除元素是不确定的。移除的# 时候会返回移除的元素的值。# pop方法演示:s1 = {11,22,33}ret = s1.pop()print(ret)33# s1 = {11,22,33}# s2 = {22,33,44}# s3 = s1.intersection(s2) #取s1和s2的交集,就是两个集合都有的元素# print(s3)# {33, 22}# s1.intersection_update(s2) #同样与difference_update类似,把两个集合的交集元素更新到s1中# print(s1)# s3 = s1.union(s2) #把两个集合合起来,去并集。如s1和s2,结果就是11,22,33,44# print(s3)# {33, 22, 11, 44}s1 = {11,22,33}s1.update([55,66,777]) #接收一个可迭代的对象,内部会自己去循环这个对象,然后把元素# 更新到集合中。相当于批量添加print(s1){33, 66, 777, 11, 22, 55}s1.update("abcdefg") #字符串也是可迭代的,会把每个字符分开,更新到集合中print(s1) |
Set Practice Questions:Suppose the script automatically collects assets. Current situation is: 1 slot: 8G 2 slot: 4G 4 slot 2G, if you do an operation, 4 slots of memory placed in 3 slots, 1 slots of memory replaced by 4G.assets have been updated, the latest data should be updated into the dictionary.
| 1234567891011 |
old_dict = { "#1": 8, "#2": 4, "#4": 2,}new_dict = { "#1": 4, "#2": 4, "#3": 2,} |
Now it's time to update the # # data to the Old_dic dictionary, delete the # # data, and update the # # value. The first thing to find out: which slots should be deleted should be updated which slots should be added to those slots
| 123 |
del_set = set (old_dict). Difference ( set (new_dict)) #取出需要删除的槽位 { ' #4 ' Code class= "As3 Plain" >} add_set = set set (old _dict) #取出需要添加的槽位 { ' #3 ' } update_set = set ( new_dict). Intersection ( set (old_dict)) # Remove Slots { } |
Python (three) set set