python for循环+列表插入问题
目标
user是个列表,每次都改变user[0]的值,再插入到后面去
问题出现
(发现结果不符合预期时增加了打印)
user_list = []
user = ['', 'Abc12345']
for i in range(0, num):
user[0] = 'test' + str(i)
user_list.append(user)
print(user_list)
print(user_list)
[[‘test0’, ‘Abc12345’]]
[[‘test1’, ‘Abc12345’], [‘test1’, ‘Abc12345’]]
[[‘test2’, ‘Abc12345’], [‘test2’, ‘Abc12345’], [‘test2’, ‘Abc12345’]]
[[‘test3’, ‘Abc12345’], [‘test3’, ‘Abc12345’], [‘test3’, ‘Abc12345’], [‘test3’, ‘Abc12345’]]
[[‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’]]
[[‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test4’, ‘Abc12345’]]
解决方法
user_list = []
index = 0
for i in range(0, num):
index += 1
user = ['test' + str(index), 'Abc12345']
user_list.append(user)
执行结果
[[‘test1’, ‘Abc12345’], [‘test2’, ‘Abc12345’], [‘test3’, ‘Abc12345’], [‘test4’, ‘Abc12345’], [‘test5’, ‘Abc12345’]]
分析
1.python的值传递和指针传递
- 对于基本数据类型的变量,变量传递给函数后,函数会在内存中复制一个新的变量,从而不影响原来的变量。(我们称此为值传递)
- 但是对于表来说,表传递给函数的是一个指针,指针指向序列在内存中的位置,在函数中对表的操作将在原有内存中进行,从而影响原有变量。 (我们称此为指针传递)
2.变量user代表了一个指针,指向一个开辟的节点。虽然改变了value值,但是内存指针仍旧指向同一个内存地址,只是对内容不停的修改
3.将需要变的字典写在循环里,就相当于每次循环申请了一个地址,把更新的值放进去