python循环中append_[Python]list.append()在for循环中每次添加的都是最后的一个元素
首先得知道三點(diǎn)。
1、程序的運(yùn)行是需要去內(nèi)存中申請(qǐng)地址的。
2、賦值操作只是對(duì)于內(nèi)存中某一塊地址的引用。
3、Python 內(nèi)置的 id()函數(shù)。 該函數(shù)從概念上可以理解為得到當(dāng)前生命下的內(nèi)存地址。
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.
由此我們可以得到以下結(jié)果:
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
在此基礎(chǔ)上去看 字典/dict :
當(dāng)聲明一個(gè)字典 info = {} 的操作時(shí)候,該字典就已經(jīng)在內(nèi)存中獲取了某一塊地址。
對(duì)該字典進(jìn)行操作時(shí),如 info['name'] = 'github' 的時(shí)候,這個(gè)字典依舊是之前所占用的地址。
可通過id 函數(shù)跟蹤得到以下代碼:
info = {}
print(id(info)) # value y
info['name'] = 'github'
print(id(info)) # value y
因此,對(duì)于你改進(jìn)前的代碼
pathlist.append(info)添加進(jìn)去的始終是同一個(gè)info,準(zhǔn)確的說,始終是同一塊地址,而這個(gè)info內(nèi)容在不停的修改。
參考以下代碼:
info = {'name': 'github'}
pathlist = [info,]
print(id(info)) # value z
print(id(pathlist[0])) # value z
然后,對(duì)于改進(jìn)后的代碼
info = {} 的操作放在了循環(huán)內(nèi),結(jié)果就是每一次循環(huán)都申請(qǐng)使用一段新的地址,只不過依舊用info來引用。
可由一下代碼對(duì)比:
info = {}
print(id(info)) # value m
info = {}
print(id(info)) # value n
兩次打印的值是不等的。
另外
第一段代碼中的
pathlist.append(info) #將dict添加進(jìn)list中
這個(gè)注釋,太 多 余 了。
希望能幫到你。
總結(jié)
以上是生活随笔為你收集整理的python循环中append_[Python]list.append()在for循环中每次添加的都是最后的一个元素的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python写入中文、用utf-16编码
- 下一篇: pythonsqlite3教程_使用 P