文章目录
Quize 1
- python中的赋值问题
在python中将一个变量赋值给另一个变量时,并不是创建了一个新的变量,而是创建了一个引用,对该引用进行修改时,原变量内容将同时被改变。
如果不希望原变量被改变,应该使用List.copy()函数,检验程序如下:
输出结果:L = [5, 7, 3, 9] print("The original list of L: ", L); print("-"*50) # ------------------------------------------------- copy of L L_copy = L.copy(); L_copy[0] = 0 print("After L_copy = L.copy(), and let L_copy[0] = 0") print(' '*5, f"L: {L}") print(' '*5, f"L_reference: {L_reference}") print("-"*50) # ------------------------------------------------ reference of L L_reference = L; L_reference[0] = 0 print("After L_reference = L, and let L_reference[0] = 0") print(' '*5, f"L: {L}") print(' '*5, f"L_reference: {L_reference}") print("-"*50) # ------------------------------------------------ therefor if L is L_reference: print("L_reference is the reference of L") else: print("L_reference is not the reference of L") if L is L_copy: print("L_copy is the reference of L") else: print("L_copy is not the reference of L")
问题来源: kaini.busy同学
参考:https://my.oschina.net/u/4505693/blog/3232657