# 字符串是不可变类型 s = "pig" """ id(s) Out[18]: 4355286776 """ s = "cat" """ id(s) Out[20]: 4324273488 """ # 字符串赋值 a = "apple" b = "apple" a == b # Out[13]: True a is b # Out[12]: True id(a) # Out[14]: 4368069552 id(b) # Out[15]: 4368069552 """ a = "red apple" b = "red apple" """ a == b Out[7]: True a is b Out[8]: False id(a) Out[5]: 4368267888 id(b) Out[6]: 4368267696 # 小整数 a = 256 b = 256 """ a == b Out[4]: True a is b Out[5]: True id(a) Out[13]: 4297652576 id(b) Out[14]: 4297652576 """ a = 257 b = 257 """ a == b Out[8]: True a is b Out[9]: False id(a) Out[10]: 4367096688 id(b) Out[11]: 4367097168 # 2 ** 8 = 256 """ # 元组 t = (0, []) t[-1].append(1) """ t Out[23]: (0, [1]) """ t[-1] += [1] """ TypeError: 'tuple' object does not support item assignment t Out[25]: (0, [1, 1]) """ t[-1] = t[-1] + [2] """ TypeError: 'tuple' object does not support item assignment t Out[28]: (0, [1, 1]) [1] + [2] Out[27]: [1, 2] """ # 字典的键 {(1, -1): "value"} # ok {(1, -1, []): "value"} # error # 列表复制 import copy # 赋值 l1 = [1, 2, 3, []] l2 = l1 l2.append(4) """ l1 Out[30]: [1, 2, 3, [], 4] l2 Out[31]: [1, 2, 3, [], 4] """ # 浅拷贝 l1 = [1, 2, 3, []] l3 = copy.copy(l1) l3.append(5) """ l1 Out[36]: [1, 2, 3, []] l3 Out[37]: [1, 2, 3, [], 5] """ l3[3].append(6) """ l1 Out[39]: [1, 2, 3, [6]] l3 Out[40]: [1, 2, 3, [6], 5] """ # 深拷贝 l1 = [1, 2, 3, []] l4 = copy.deepcopy(l1) l4[-1].append(7) """ l1 Out[42]: [1, 2, 3, []] l4 Out[43]: [1, 2, 3, [7]] """ # 复制列表 l1 = [1, 2, 3] l2 = l1 l3 = l1[:] # 推荐 """ id(l1) Out[45]: 4367794824 id(l2) Out[46]: 4367794824 id(l3) Out[47]: 4367785032 """ # 元组复制 t1 = (1, 2, 3) t2 = t1 """ t1 is t2 Out[48]: True """ # 二维矩阵 l = [0, 0, 0] * 3 """ l Out[50]: [0, 0, 0, 0, 0, 0, 0, 0, 0] """ matrix = [[0, 0, 0]] * 3 # 会引用同一个列表 """ matrix Out[52]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] matrix[0][0]=1 matrix Out[54]: [[1, 0, 0], [1, 0, 0], [1, 0, 0]] """ matrix = [[0, 0, 0] for i in range(3)] # 推荐 """ matrix Out[56]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] matrix[0][0]=1 matrix Out[58]: [[1, 0, 0], [0, 0, 0], [0, 0, 0]] """ # None比较 a = None b = None """ a == b Out[20]: True a is b Out[19]: True id(a) Out[21]: 4297328656 id(b) Out[22]: 4297328656 """ a = 1 a is None # is判断id # Out[60]: False a = None a is None # Out[62]: True # 排序 s = [1, 3, 2] s.sort() # return None 原地操作 s # Out[65]: [1, 2, 3] sorted(s) # Out[66]: [1, 2, 3] # 返回新列表 sorted((1, 2, 3)) # 可迭代即可 # Out[68]: [1, 2, 3] tuple(1, 2, 3) # TypeError: tuple() takes at most 1 argument (3 given) # 检查a is b 的时候,其实相当于检查 id(a) == id(b)。 # 检查 a == b 的时候,实际是调用了对象 a 的 __eq()__ 方法,a == b 相当于 a.__eq__(b) # python列表可以存不同对象,其实是只保存了对象的地址,地址的大小是固定的