Python 中的 is 和 == 编码和解码
一 is 与 == 区别
== 比较 比较的是值
例如:
1 a = 'alex' 2 b = 'alex' 3 print(a == b) #True 4 5 a = 10 6 b = 10 7 print(a == b) #True 8 9 a = [1,2,3] 10 b = [1,2,3] 11 print(a == b) #True 12 13 a = {1:2,'1':'b'} 14 b = {1:2,'1':'b'} 15 print(a == b) #True
总结:== 可以比较任何字类型, 字符串, 列表, 数字, 元组 ,字典
id() 查看内存地址 内存地址可变
1 a = 'alex' 2 print(id(a)) # 2761240786064 3 4 n = 10 5 print(id(n)) # 1789685056 6 7 n = [1,2,3] 8 print(id(n)) # 2629987043976
总结: id() 返回的是内存地址 所有的类型都有内存地址
is 是比较 比较的是内存地址 小数据池
1 # 字符串 2 a = 'alex' 3 b = 'alex' 4 print(a is b) #True 5 # 数字 6 a = 10 7 b = 10 8 print(a is b) #True 9 10 a = -5 11 b = -5 12 print(a is b) #True 13 14 a = -6 15 b = -6 16 print(a is b) #False 17 18 a = 257 19 b = 257 20 print(a is b) #False 在终端上显示 21 22 a = 'alex@' 23 b = 'alex@' 24 print(a is b) #False 在终端上显示 25 26 a = 'a' * 20 27 b = 'a' * 20 28 print(a is b) #True 29 30 a = 'a' *21 31 b = 'a' *21 32 print(a is b) #False 33 34 a = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 35 b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' 36 print(a is b) #True
总结: 数字小数据池的范围是 -5 ~256
字符串中如果有特殊字符他们的内存地址就不一致
字符串中单个*20以内的数他们的内存地址一致,单个*20以上内存地址就不一致
在python中一般的字符串都是会被缓存的. 为了节约内存
a = "alex@wusir"
b = "alex@wusir"
print(id(a), id(b))
1 # 列表 2 lis = [1,2,3] 3 lis1 = [1,2,3] 4 print(lis is lis1) #False 5 6 # 元组 7 tu = (1,2,3,4) 8 tu1 = (1,2,3,4) 9 print(tu is tu1) #False 10 11 # 字典 12 dic = {1:'a','f':2} 13 dic1 = {1:'a','f':2} 14 print(dic is dic1) #False
总结: 字典 ,元组 ,列表 内存地址都不一致
编码与解码
重点
encode(编码方式)---------------拿到明文编码后对应的字节
decode(解码方式)---------------将编码后的字节解码成对应的明文
注意 : 用什么进行编码就用什么进行解码 不然会懵逼
例题
1 cars = ["鲁A12345","鲁B12345", "沪B45678", "黑A12345", "黑A12345","黑A12355","黑A12655"] 2 locals = {"鲁": "山东", "沪": '上海', "黑": '黑龙江'} 3 dic = {} 4 for ca in cars: 5 s = ca[0] # 获取车牌简称 6 sheng = locals[s] # 根据车牌简称获取字典中value 并赋值 7 #开始计数g 8 if dic.get(sheng) == None: #如果获取当前位置,找不到车辆 9 dic[sheng] = 1 #直接计数 , 然后添加字典value 10 else: 11 dic[sheng] = dic[sheng] + 1 # 对车牌数量进行统计, 累加更value 12 print(dic)