日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python循环中append_[Python]list.append()在for循环中每次添加的都是最后的一个元素

發(fā)布時(shí)間:2025/6/17 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python循环中append_[Python]list.append()在for循环中每次添加的都是最后的一个元素 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

首先得知道三點(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。