python字典问题
大家讲道理
大家讲道理 2017-04-18 10:14:44
0
4
311
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
迷茫
>>> d = {}
>>> help(d.fromkeys)
Help on built-in function fromkeys:

fromkeys(...)
    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
    v defaults to None.

The values ​​of all 5 elements are v, and as v is a complex type, it is passed by reference instead of value.

Ty80

References, they all point to the same []. . .

迷茫

Because those lists are the same.

巴扎黑

Because [] 只会被初始化一次,然后所有的key都会引用到它,也就是浅拷贝, it can be implemented in another way:
First way:
in python3

d = {i: [] for i in range(5)}
d[1].append({'k': 'v'})

The second type:

from collections import defaultdict
d = defaultdict(list)
d[1].append({'k': 'v'})

copy.deepcopyI don’t really want to use it anymore

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