-->the start
养成好习惯,每次上课的内容都要写好笔记。
一、整型
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 """ 5 int类的几个内建方法 6 """ 7 8 # 返回商和余数的元祖 9 all_pages = 95 10 per_page = 10 11 pages = all_pages.__divmod__(per_page) 12 print(pages) 13 14 # __ceil__ ?? 15 num = 19 16 print(num.__ceil__()) 17 18 # 绝对值 19 num1 = -19 20 print(abs(num1)) 21 print(num1.__abs__()) 22 23 # 相加 24 num2 = 5 25 print(num1+num2) 26 print(num2.__add__(num1)) 27 28 # 布尔值,非零返回真, 29 num3 = 0 30 print(num2.__bool__()) 31 print(num3.__bool__()) 32 33 # 判断是是否相等 34 print(num3.__eq__(num2)) 35 36 # 返回浮点 37 print(num2.__float__()) 38 39 # 地板除 19//5 40 print(num.__floordiv__(num2)) 41 42 # 大于等于 43 print(num.__ge__(num2)) 44 45 # 大于 46 print(num.__gt__(num2)) 47 48 # 哈希 49 print(num.__hash__()) 50 51 # __index__ :索引 用于切片,数字无意义 52 # x[y: z] <==> x[y.__index__(): z.__index__()] 53 54 # __init__ :构造方法 55 56 # 转换为整数 57 # x.__int__() <==> int(x) 58 59 # __invert__ :取反 x.__invert__() <==> ~x 60 print(num.__invert__()) 61 62 # 小于等于 63 print(num.__le__(num2)) 64 65 # 小于 66 print(num.__lt__(num2)) 67 68 # __lshift__ :左移位 69 int_temp1 = 1 70 int_temp2 = 4 71 print(int_temp1.__lshift__(int_temp2)) 72 73 # 求模 x.__mod__(y) <==> x%y 74 print(num.__mod__(num2)) 75 76 # 相乘 x.__mul__(y) <==> x*y 77 print(num.__mul__(num2)) 78 79 # 取反 80 print(num.__neg__()) 81 82 # 不等于 83 print(num.__ne__(num2)) 84 85 # 取正数 ??? 86 print(num1.__pos__()) 87 88 # 乘方 89 print(num.__pow__(2)) 90 91 # 右加(以下前缀为r的都是右;前缀为l的都是左) 92 print(num.__radd__(num1)) 93 94 # 右或 95 print(int_temp1.__rand__(int_temp2)) 96 97 # 右除以左,返回商和余数 98 print(per_page.__rdivmod__(all_pages)) 99 100 # 转换为解释器可读取的形式 101 print(num.__repr__()) 102 103 # 转换为字符串 104 print(num.__str__()) 105 print(type(num.__str__())) 106 107 # 求差 x.__sub__(y) <==> x-y 108 print(num.__sub__(num2)) 109 110 # x.__truediv__(y) <==> x/y 111 print(num.__truediv__(num2)) 112 113 # 异或 :按位不一样的为真,一样的为假。x.__xor__(y) <==> x^y 114 115 # 返回->表示该数字时占用的最少位数 116 print(bin(37)) 117 print((37).bit_length()) 118 119 # 返回->共轭数 120 int_temp1 = 37 121 print(int_temp1.conjugate()) 122 123 '''这俩方法暂时没搞懂。。。 124 def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 125 """ 126 int.from_bytes(bytes, byteorder, *, signed=False) -> int 127 128 Return the integer represented by the given array of bytes. 129 130 The bytes argument must be a bytes-like object (e.g. bytes or bytearray). 131 132 The byteorder argument determines the byte order used to represent the 133 integer. If byteorder is 'big', the most significant byte is at the 134 beginning of the byte array. If byteorder is 'little', the most 135 significant byte is at the end of the byte array. To request the native 136 byte order of the host system, use `sys.byteorder' as the byte order value. 137 138 The signed keyword-only argument indicates whether two's complement is 139 used to represent the integer. 140 """ 141 pass 142 143 def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ 144 """ 145 int.to_bytes(length, byteorder, *, signed=False) -> bytes 146 147 Return an array of bytes representing an integer. 148 149 The integer is represented using length bytes. An OverflowError is 150 raised if the integer is not representable with the given number of 151 bytes. 152 153 The byteorder argument determines the byte order used to represent the 154 integer. If byteorder is 'big', the most significant byte is at the 155 beginning of the byte array. If byteorder is 'little', the most 156 significant byte is at the end of the byte array. To request the native 157 byte order of the host system, use `sys.byteorder' as the byte order value. 158 159 The signed keyword-only argument determines whether two's complement is 160 used to represent the integer. If signed is False and a negative integer 161 is given, an OverflowError is raised. 162 """ 163 pass 164 '''
二、长整型
三、浮点型
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 float的内建方法 7 """ 8 9 # 返回分子分母数构成的元祖 10 f1 = 10.0 11 f2 = 0.0 12 f3 = -0.25 13 14 print(f1.as_integer_ratio()) 15 print(f2.as_integer_ratio()) 16 print(f3.as_integer_ratio()) 17 print(f3.as_integer_ratio()) 18 19 # 返回共轭复数 conjugate(self, *args, ***kwargs) 20 21 # 将十六进制数转换为浮点数 22 print(float.fromhex('0x1.ffffp10')) 23 24 # 将浮点数转换为十六进制数 25 print(2047.984375.hex()) 26 27 # 判断浮点数是不是整数 28 f1 = 10.2 29 f2 = 10.0 30 print(f1.is_integer()) 31 print(f2.is_integer())
四、字符串
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 str类的内建方法练习 7 8 """ 9 name1 = 'alex' 10 name2 = str('ERIC') # 调用字符串类的__init__()方法 11 print(type(name1)) 12 print(dir(name1)) # 打印出类的成员 13 14 # 包含 15 result = name1.__contains__('ex') 16 print(result) 17 result = 'ex' in name1 18 print(result) 19 20 # 等于 21 print(name1.__eq__(name2)) 22 23 # 字符串按照format_spec格式化 24 """ 25 format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] 26 27 fill ::= <any character> 28 29 align ::= "<" | ">" | "=" | "^" 30 31 sign ::= "+" | "-" | " " 32 33 width ::= integer 34 35 precision ::= integer 36 37 type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" 38 39 fill是表示可以填写任何字符。 40 41 align是对齐方式,<是左对齐, >是右对齐,^是居中对齐。 42 43 sign是符号, +表示正号, -表示负号。 44 45 width是数字宽度,表示总共输出多少位数字。 46 47 precision是小数保留位数。 48 49 type是输出数字值是的表示方式,比如b是二进制表示;比如E是指数表示;比如X是十六进制表示。 50 """ 51 # 共20个字符,name1右对齐 52 print(name1.__format__('>20')) 53 54 # 返回小写 55 result = name2.casefold() 56 print(result) 57 58 # 居中 59 # print('*' * 8 %s '*' * 8 % name1) 60 result = name1.center(20, '*') 61 print(result) 62 63 # 获取指定标签属性的值 64 print(name1.__getattribute__('index')) 65 66 # x.__getitem__(y) <==> x[y](返回str[key]) 67 print(name1.__getitem__(1)) 68 69 # 大于等于 70 print(name1.__ge__(name2)) 71 72 # 大于 73 print(name1.__gt__(name2)) 74 75 # 哈希 76 print(name1.__hash__()) 77 78 # 返回一个字符串的迭代 79 for i in name1.__iter__(): 80 print(i) 81 82 # 返回字符串的长度 83 print(name1.__len__()) 84 85 # 首字母大写 86 print(name1.capitalize()) 87 88 # 返回将小写字符串转换为大写,大写转换为小写 89 name3 = "AlEx" 90 print(name1.swapcase()) 91 print(name2.swapcase()) 92 print(name3.swapcase()) 93 94 # 返回str的小写 95 print(name2.casefold()) 96 97 # 将字符串转换为标题:每个单词的首字母大写 98 str_temp = "eric is humor!" 99 print(str_temp.title()) 100 101 # 居中 下例为:20个字符的宽度以'*'号填充,name1居中 102 print(name1.center(20, '*')) 103 104 # count 计数 105 str1 = 'adasafafdsfqadasddfa' 106 result = str1.count('a') 107 print(result) 108 109 # encode 编码 110 result = name1.encode('gbk') 111 print(result) 112 113 # endswith 以'xxx'结束,后面可跟索引 114 result = str1.endswith('a') 115 print(result) 116 result = str1.endswith('s', 2, 4) 117 print(result) 118 119 # 替换tabs tabsize默认为8 120 name_temp = 'a\nlex' 121 print(name_temp.expandtabs()) 122 print(len(name_temp.expandtabs())) 123 124 # 查找 返回索引值 125 print(name1.find('e')) 126 127 # 格式化 128 str_temp = '{} is humor!' 129 print(str_temp.format(name2)) 130 131 # 按映射格式化 132 # format_map(self, mapping) 133 134 # 返回索引值 index(self, sub, start=None, end=None) 没有返回0 135 print(name1.index('l')) 136 137 str_temp = 'a1b2c3' 138 # 判断字符串是否是字母或数字 139 print(str_temp.isalnum()) 140 141 # 判断字符串是否只是字母 142 print(str_temp.isalpha()) 143 144 # 判断字符串中是否只包含十进制字符 145 str_temp = '0.3a0.4b' 146 str_temp1 = '0.3' 147 print(str_temp.isdecimal()) 148 print(str_temp1.isdecimal()) 149 150 # 判断字符串中是否只有数字 151 str_temp = b'12345' 152 str_temp1 = '12345' 153 str_temp2 = '四' 154 print(str_temp.isdigit()) 155 print(str_temp1.isdigit()) 156 print(str_temp2.isdigit()) 157 158 print("line:148".center(20, "=")) 159 160 # 判断是否是标识符 161 str_temp = 'class' 162 print(str_temp.isidentifier()) 163 164 # 判断字符串中是否都是小写 165 str_temp = 'eric' 166 str_temp1 = 'Eric' 167 print(str_temp.islower()) 168 print(str_temp1.islower()) 169 170 # 判断字符串中是否都是数值型字符串 171 # 'bytes' object has no attribute 'isnumeric' 172 str_temp = '12345' 173 str_temp1 = '12345' 174 str_temp2 = '四' 175 str_temp3 = '壹佰贰拾叁' 176 print(str_temp.isnumeric()) 177 print(str_temp1.isnumeric()) 178 print(str_temp2.isnumeric()) 179 print(str_temp3.isnumeric()) 180 181 # 判断是否可被打印 182 str_temp = 'abc' 183 print(str_temp.isprintable()) 184 185 # 是否为空格 186 str_temp = ' ' 187 print(str_temp.isspace()) 188 189 # 判断是否为标题 (所有首字母大写) 190 str_temp = 'eric is humor!' 191 str_temp1 = 'Eric Is Humor!' 192 print(str_temp.istitle()) 193 print(str_temp1.istitle()) 194 195 print('line:185'.center(20, '=')) 196 197 # 判断字符串是否全为大写 198 str_temp = 'eric is humor!' 199 str_temp1 = 'Eric Is Humor!' 200 str_temp2 = 'ERIC IS HUMOR!' 201 print(str_temp.isupper()) 202 print(str_temp1.isupper()) 203 print(str_temp2.isupper()) 204 205 # 字符串的拼接 join(self, iterable) 206 str_temp = "ERIC" 207 print(':'.join(str_temp)) 208 209 # 左对齐 210 str_temp = "eric" 211 print(str_temp.ljust(20, '*')) 212 # 右对齐 213 print(str_temp.rjust(20, '*')) 214 215 # 将字符串转换为小写 216 str_temp = "ERIC" 217 print(str_temp.lower()) 218 # 将字符串转换为大写 219 str_temp1 = "eric" 220 print(str_temp1.upper()) 221 222 # strip()移除字符串前后的指定字符;lstrip()移除左边指定字符 默认为移除空格;rstrip()移除右边指定字符 223 str_temp = " eric is humor ! " 224 print(str_temp.strip()) 225 print(str_temp.lstrip()) 226 print(str_temp.rstrip()) 227 str_temp1 = "eric is humor!" 228 print(str_temp1.lstrip('eric')) 229 print(str_temp1.rstrip('mor!')) 230 231 # maketrans(self, *args, **kwargs)和translate() 232 str_temp = '654321123789' 233 map_temp = str.maketrans('123', 'abc') 234 map_temp1 = str.maketrans('123', 'abc', '789') 235 print(str_temp.translate(map_temp)) 236 print(str_temp.translate(map_temp1)) 237 238 # 按照指定分隔符将字符串分割,返回元祖 239 # 如果字符串包含指定的分隔符,则返回一个三元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。 240 # 如果字符串不包含指定的分隔符,则返回一个三元的元祖,第一个为字符串本身,第二个、第三个为空字符串。 241 str_temp = "www.google.com" 242 print(str_temp.partition('google')) 243 print(str_temp.partition('www')) 244 print(str_temp.partition('wxw')) 245 246 # 右侧开始分隔 247 print(str_temp.partition('o')) 248 print(str_temp.rpartition('o')) 249 250 # Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 251 str_temp = "www.google.com" 252 print(str_temp.replace('.', '-', 1)) 253 254 # 右查找 255 str_temp.rfind('.') 256 257 # 右索引 258 str_temp.rindex('.') 259 260 # 分割 261 str_temp = "www.google.com" 262 print(str_temp.split('o', 2)) 263 # 右分隔 264 print(str_temp.rsplit('o', 2)) 265 266 print('line:252'.center(20, '=')) 267 268 # 行分割 269 str_temp = """ 270 eric 271 is 272 humor 273 ! 274 """ 275 print(str_temp.splitlines()) 276 277 # 以什么开始 278 str_temp = "eric is humor!" 279 print(str_temp.startswith('eric')) 280 281 # 返回指定长度的字符串,原字符串右对齐,前面补0 282 str_temp = "23" 283 print(str_temp.zfill(20))
五、列表
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 dict类的内建方法 7 """ 8 # 增加 :append object to end 9 l1 = list([1, 2, 3, ]) 10 l1.append(4) 11 print(l1) 12 l1.append([5, 6, 7,]) 13 print(l1) 14 15 # 清空 16 print(l1.clear()) 17 18 # 复制 19 l1 = [1, 2, 3, ] 20 print(l1.copy()) 21 22 # 计数 23 l1 = [1, 1, 2, 1, 3, 2] 24 print(l1.count(1)) 25 26 # 扩展 : extend(self, iterable) 27 l1 = [1, 2, 3, ] 28 l1.extend((5, 6, )) 29 print(l1) 30 l1.extend('abc') 31 print(l1) 32 33 # 索引 34 print(l1.index(3)) 35 36 # 插入:index(self, value, start=None, stop=None) 37 l1.insert(5, 0) 38 print(l1) 39 40 # 弹出 : pop(self, index=None) 41 print(l1.pop()) 42 print(l1.pop(5)) # 返回l1[5] 43 44 # 移除 :remove(self, value) 45 l1 = [1, 2, 3, 4, 5, 6, 'a'] 46 l1.remove(6) 47 print(l1) 48 print(l1.remove('a')) # 返回None 49 print(l1) 50 51 print('line:51'.center(20, '=')) 52 53 # 反转 54 l1 = [1, 2, 3, 4, 5, ] 55 l1.reverse() 56 print(l1) 57 58 # 排序 :sort(self, key=None, reverse=False) 59 l1 = ['123', 'xyz', '789', 'uvw', '哈哈'] 60 l1.sort() 61 print(l1) 62 l1.sort(reverse=True) 63 print(l1)
六、字典
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 dict内建的方法 7 * 字典是无序的 8 * from collections import OrderedDict # 有序字典 9 """ 10 11 dic1 = {'k1': 'v1', 'k2': 'v2', } 12 print(dic1) 13 dic1 = dict(k1='v1', k2='v2') 14 print(dic1) 15 16 # 清空 17 dic1.clear() 18 print(dic1) 19 20 # 复制 copy()分为深拷贝和浅拷贝 此处为浅拷贝(shallow copy) 21 22 # fromkeys: Returns a new dict with keys from iterable and values equal to value. 23 dic2 = dict.fromkeys(['k1', 'k2', ], 1) 24 print(dic2) 25 26 # 取得指定键的值-> get(self, k, d=None) 27 dic1 = {'k1': 'v1', 'k2': 'v2'} 28 print(dic1.get('k1')) 29 print(dic1.get('k3', 'No!!!')) 30 31 # 键值对的集合:items() 32 print(dic1.items()) 33 for i in dic1.items(): 34 print(i) 35 36 # 键值 37 print(dic1.keys()) 38 for i in dic1.keys(): 39 print(i) 40 41 print('line:39'.center(20, '=')) 42 43 # 弹出: 移除指定的键,返回对应的值 -> pop(self, k, d=None) 44 print(dic1.pop('k1')) 45 print(dic1) 46 print(dic1.pop('k3', 'ERROR!!!')) 47 48 # popitem() 弹出一个键值对组成的元祖,字典为空弹出时报错 49 dic1 = {'k1': 'v1', 'k2': 'v2'} 50 print(dic1.popitem()) 51 print(dic1) 52 print(dic1.popitem()) 53 54 # 为字典设置默认值 55 dic1 = {} 56 dic1.setdefault('k1', 'v1') 57 dic1.setdefault('k2') 58 print(dic1) 59 60 # 升级字典 61 dic1 = {'k1': 'v1', } 62 dic2 = {'k2': 'v2', 'k3': 'v3', } 63 dic1.update(dic2) 64 print(dic1) 65 print(dic2) 66 67 # 返回字典的值 68 dic1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3', } 69 print(dic1.values()) 70 for i in dic1.values(): 71 print(i) 72 73 # 课堂小练习 74 # [11, 22, 33, 44, 55, 66, 77, 88, 99, ...]大于66的保存在字典的第一个key的值中,小于等于66的放到第二个key的值中 75 # {'key1':大于66的, 'key2':小于等于66的} 76 77 l1 = [11, 22, 33, 44, 55, 66, 77, 88, 90, 99, ] 78 dic = {} 79 for i in l1: 80 if i > 66: 81 if 'key1' in dic.keys(): 82 dic['key1'].append(i) 83 else: 84 dic['key1'] = [i, ] 85 else: 86 if 'key2' in dic.keys(): 87 dic['key2'].append(i) 88 else: 89 dic['key2'] = [i, ] 90 print(dic)
七、元祖
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 tuple的内建方法 7 * -元祖的元素不可变 8 * -元祖的元素的元素可以变 9 """ 10 11 # 计数 12 t1 = (1, 1, 2, 3, 4, 4, 1) 13 print(t1.count(1)) 14 15 # 索引 16 print(t1.index(2)) 17 18 print('line:18'.center(20, '=')) 19 20 t1 = (1, 2, {'k1': 'v1'}) 21 t1[2]['k1'] = 2 22 print(t1) 23 print(t1[2])
八、集合
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 集合(set)的内建功能练习 7 集合(set)是一个无序且不重复的元素的集合。 8 """ 9 10 s1 = set((1, 2, 3, 3)) 11 print(s1) 12 13 # add(self, *args, **kwargs) 给集合添加一个新的元素 14 s1.add(4) 15 s1.add((4, 5)) 16 print(s1) 17 18 # clear(self, *args, **kwargs) 移除集合内的所有元素 19 s1.clear() 20 print(s1) 21 22 # copy 返回一个集合的浅拷贝 23 s1 = {1, 2, 3} 24 s2 = s1.copy() 25 print(s2) 26 27 # difference() 返回两个或多个集合之间不同的元素的集合 28 s1 = {1, 2, 3} 29 s2 = {1, 3, 5} 30 s4 = {2, 4, 6, 8} 31 s3 = s1.difference(s2) # 把s1里有的,s2里没有的返回给s3 32 s5 = s4.difference(s1) # 把s4里有的,s1里没有的返回给s5 33 s = "s1:{0}\ns2:{1}\ns3:{2}\ns4:{3}" 34 print(s.format(s1, s2, s3, s5)) 35 36 # difference_update() # 从集合里移除另一个集合里的所有元素 37 s4.difference_update(s1) # 从s4里面移除s1里也有的所有元素 38 print(s4) 39 40 # discard() 移除集合里的一个元素,如果给的参数不是集合里的元素,则什么都不做 41 s4.discard(2) 42 print(s4) 43 s4.discard(4) 44 print(s4) 45 46 # intersection() 返回两个集合的交集的集合 47 s1 = {1, 2, 3} 48 s2 = {1, 3, 5} 49 s3 = s1.intersection(s2) 50 print(s3) 51 52 print('line:52'.center(20, '*')) 53 # intersection_update() sa.intersection_update(sb):用sa和sb的交集返回给sa 54 s1 = {1, 2, 3} 55 s2 = {1, 3, 5} 56 s1.intersection_update(s2) 57 print(s1) 58 59 # isdisjoint() # 判断两个集合有无交集,无交集返回True 60 s1 = {1, 2, 3} 61 s2 = {1, 3, 5} 62 s3 = {2, 4, 6} 63 print(s1.isdisjoint(s2)) 64 print(s2.isdisjoint(s3)) 65 66 # issubset() sa.issubset(sb):判断sa是否为sb的子集 67 s1 = {1, 3, 5} 68 s2 = {1, 3} 69 print(s2.issubset(s1)) 70 71 # issuperset sa.issuperset(sb):判断sa是否包含sb 72 print(s1.issuperset(s2)) 73 74 # pop() 移除并返回一个任意元素,集合为空时会raise KeyError 75 s1 = {1, 3, 5} 76 print(s1.pop()) 77 print(s1) 78 79 # remove() 从集合中移除一个元素,没有此元素时,raise KeyError 80 s1 = {1, 3, 5} 81 s1.remove(3) 82 print(s1) 83 84 print('line:84'.center(30, '*')) 85 86 # symmetric_difference() 返回两个集合的非交集元素到一个新集合 87 s1 = {1, 2, 5} 88 s2 = {1, 3, 5, 7} 89 s3 = s1.symmetric_difference(s2) 90 print(s3) 91 92 # symmetric_difference_update() sa.symmetric_difference_update(sb):将sa、sb的非交集元素返回给sa 93 s1 = {1, 2, 5} 94 s2 = {1, 3, 5, 7} 95 s1.symmetric_difference_update(s2) 96 print(s1) 97 98 # union() sa.union(sb):返回sa、sb的合集 99 s1 = {1, 2, 3} 100 s2 = {1, 3, 5} 101 s3 = s1.union(s2) 102 print(s3) 103 104 # update() sa.update(sb):将sa、sb的合集返回给sa 105 s1 = {1, 3, 5} 106 s2 = {2, 4, 6} 107 s1.update(s2) 108 print(s1)
集合应用举例:
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 集合介绍 7 """ 8 # 示例 9 old_dict = { 10 "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capacity': 80}, 11 "#2": {'hostname': 'c1', 'cpu_count': 2, 'mem_capacity': 80}, 12 "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capacity': 80}, 13 } 14 new_dict = { 15 "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capacity': 800}, 16 "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capacity': 80}, 17 "#4": {'hostname': 'c2', 'cpu_count': 2, 'mem_capacity': 80}, 18 } 19 20 # 旧字典没有新字典有的就是需要删除的数据 21 # 旧字典有新字典没有的就是需要增加的数据 22 # 旧字典和新字典都有的就是(可能)需要更新的数据 23 24 # 该示例主要是字典的第一层key为例: 25 # 将旧字典的第一层key转换成集合 26 set_old = set(old_dict.keys()) 27 # 将新字典的第一层key转换成集合 28 set_new = set(new_dict.keys()) 29 # 需要更新的数据就是取新、旧集合的交集 30 update_list = list(set_old.intersection(set_new)) 31 # 需要删除的数据就是取旧集合与新集合的不同 32 delete_list = list(set_old.difference(set_new)) 33 # 需要增加的数据就是取新集合与旧集合的不同 34 add_list = list(set_new.difference(set_old)) 35 36 s_tmp = 'update_list:{0}\ndelete_list:{1}\nadd_list:{2}' 37 print(s_tmp.format(update_list, delete_list, add_list))
<-- the end