[Python]list.append()在for循环中每次添加的都是最后的一个元素
迷茫
迷茫 2017-04-17 16:39:44
0
2
583
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
阿神

First you need to know three things.
1. To run the program, you need to apply for an address in the memory.
2. The assignment operation is just a reference to a certain address in the memory.
3. Python’s built-in id() function. This function can be conceptually understood as getting the memory address of the current life.

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.

From this we can get the following results:

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

Look at dictionary/dict based on this:

When declaring a dictionary info = {} operation, the dictionary has already obtained a certain address in the memory.
When operating on the dictionary, such as info['name'] = 'github', the dictionary is still the address it occupied before.
The following code can be traced through the id function:

info = {}                       
print(id(info))                 # value y

info['name'] = 'github'
print(id(info))                 # value y

Therefore, for the code before your improvement
pathlist.append(info) always adds the same info. To be precise, it is always the same address, and the content of this info is constantly modified.
Refer to the following code:

info = {'name': 'github'}
pathlist = [info,]

print(id(info))                 # value z
print(id(pathlist[0]))          # value z

Then, for the improved code
info = {} operation is placed in the loop. The result is that each loop applies for a new address, but it is still referenced by info.
You can compare it with the following code:

info = {}
print(id(info))                 # value m

info = {}
print(id(info))                 # value n

The values ​​printed twice are not equal.

In addition
in the first code
pathlist.append(info) #Add dict to the list
This comment is too too many more.

Hope this helps.

Ty80

Original code

listDirectory finally returns

[info, info, info...]

And info will be updated every time it loops, but it will eventually be

{'name': last_loop_item}

So there will be that result

Update code

The updated code is more intuitive.
Every time info is a newly generated dict, append is the result of each loop

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template