search

Home  >  Q&A  >  body text

python字典问题

大家讲道理大家讲道理2949 days ago312

reply all(4)I'll reply

  • 迷茫

    迷茫2017-04-18 10:16:44

    >>> 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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:16:44

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

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:16:44

    Because those lists are the same.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:16:44

    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

    reply
    0
  • Cancelreply