# 关于自己写的代码有个逻辑没有问题,但是代码有问题的错误。本质上是关于“拷贝”和“赋值”的错误。 # 我想将每次大循环后x["x1"]的结果保存到a中。 # 即:a: [[0, 1], [0, 1, 0, 1]] # 但是我得到的结果:[[0, 1, 0, 1], [0, 1, 0, 1]] ''' python 列表的赋值:a = [1,2,3], b = a;相当于a和b都指向同一块内存空间;即指针相同; python 列表的拷贝:a = [1,2,3], b = a;相当于b在内存中开辟了另一块内存空间,存储的值为a列表的值; ''' import copy print("-"*100, "“赋值”代码", "-"*100) # TODO 1. “赋值”代码 x = { "x1": [], "x2": [] } a = [] for i in range(2): for j in range(2): x["x1"].append(j) a.append(x["x1"]) for i in range(len(a)): print("id(a[i])", id(a[i])) print("value(a[i])", a[i]) # TODO 2. “拷贝”代码 print("-"*100, "“拷贝”代码", "-"*100) x = { "x1": [], "x2": [] } a = [] for i in range(2): for j in range(2): x["x1"].append(j) a.append(copy.copy(x["x1"])) for i in range(len(a)): print("id(a[i])", id(a[i])) print("value(a[i])", a[i]) ''' ---------------------------------------------------------------------------------------------------- “赋值”代码 ---------------------------------------------------------------------------------------------------- id(a[i]) 3047084190464 value(a[i]) [0, 1, 0, 1] id(a[i]) 3047084190464 value(a[i]) [0, 1, 0, 1] ---------------------------------------------------------------------------------------------------- “拷贝”代码 ---------------------------------------------------------------------------------------------------- id(a[i]) 3047084210816 value(a[i]) [0, 1] id(a[i]) 3047084190464 value(a[i]) [0, 1, 0, 1] # 解释 3047084190464 == 3047084190464 :第一次,赋值相当于多个引用,指针 3047084210816 == 3047084190464 :第二次,拷贝相当于新开辟空间存储 '''
标签:PYTHON,3047084190464,print,拷贝,x1,id,赋值 From: https://www.cnblogs.com/xiao-yu-/p/16597605.html