python循环中append_[Python]list.append()在for循环中每次添加的都是最后的一个元素
首先得知道三點。
1、程序的運行是需要去內存中申請地址的。
2、賦值操作只是對于內存中某一塊地址的引用。
3、Python 內置的 id()函數。 該函數從概念上可以理解為得到當前生命下的內存地址。
id(object)
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.
由此我們可以得到以下結果:
a = 1
b = 1
c = a
d = b
print(id(1)) # value x
print(id(a)) # value x
print(id(b)) # value x
print(id(c)) # value x
print(id(d)) # value x
print(id(1) == id(a) == id(b) == id(c) == id(d)) # True
在此基礎上去看 字典/dict :
當聲明一個字典 info = {} 的操作時候,該字典就已經在內存中獲取了某一塊地址。
對該字典進行操作時,如 info['name'] = 'github' 的時候,這個字典依舊是之前所占用的地址。
可通過id 函數跟蹤得到以下代碼:
info = {}
print(id(info)) # value y
info['name'] = 'github'
print(id(info)) # value y
因此,對于你改進前的代碼
pathlist.append(info)添加進去的始終是同一個info,準確的說,始終是同一塊地址,而這個info內容在不停的修改。
參考以下代碼:
info = {'name': 'github'}
pathlist = [info,]
print(id(info)) # value z
print(id(pathlist[0])) # value z
然后,對于改進后的代碼
info = {} 的操作放在了循環(huán)內,結果就是每一次循環(huán)都申請使用一段新的地址,只不過依舊用info來引用。
可由一下代碼對比:
info = {}
print(id(info)) # value m
info = {}
print(id(info)) # value n
兩次打印的值是不等的。
另外
第一段代碼中的
pathlist.append(info) #將dict添加進list中
這個注釋,太 多 余 了。
希望能幫到你。
總結
以上是生活随笔為你收集整理的python循环中append_[Python]list.append()在for循环中每次添加的都是最后的一个元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python写入中文、用utf-16编码
- 下一篇: pythonsqlite3教程_使用 P