zoukankan      html  css  js  c++  java
  • day②:字典的fromkeys方法

    start

    ##fromkeys方法本身就是把所有的key都指向同一个对象了
    >>> c=dict.fromkeys(range(5),[])                 
    >>> c
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> c[0].append({"B":{123}})
    >>> c
    {0: [{'B': set([123])}], 1: [{'B': set([123])}], 2: [{'B': set([123])}], 3: [{'B': set([123])}], 4: [{'B': set([123])}]}
    >>> c[0].append(1)          
    >>> c
    {0: [{'B': set([123])}, 1], 1: [{'B': set([123])}, 1], 2: [{'B': set([123])}, 1], 3: [{'B': set([123])}, 1], 4: [{'B': set([123])}, 1]}

    ##怎么解决我只想修改c[0]里面的值value呢?
    解决:先指向另一个列表对象
    >>> c=c.fromkeys(range(5),[])                    
    >>> c
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> c[0]=[]
    >>> c[0].append({"B":{123}}) 
    >>> c
    {0: [{'B': set([123])}], 1: [], 2: [], 3: [], 4: []}
    >>> c[0].append(1)
    >>> c
    {0: [{'B': set([123])}, 1], 1: [], 2: [], 3: [], 4: []}
    >>> 



    ##直接定义字典
    >>> b={0: [], 1: [], 2: [], 3: [], 4: []}
    >>> b[0].append({"B":{123}})
    >>> b
    {0: [{'B': set([123])}], 1: [], 2: [], 3: [], 4: []}
    >>> b[0].append(1)
    >>> b
    {0: [{'B': set([123])}, 1], 1: [], 2: [], 3: [], 4: []}


    ##不用fromkeys生成一个大字典的办法
    >>> c={}
    >>> c
    {}
    >>> for i in range(5):
    ...     c[i]=[]
    ... 
    >>> c
    {0: [], 1: [], 2: [], 3: [], 4: []}
    end




  • 相关阅读:
    1004. Counting Leaves (30)
    51Nod 1272 最大距离 (栈或贪心)
    D
    M
    N
    F
    E
    L
    A. Office Keys ( Codeforces Round #424 (Div. 1, rated, based on VK Cup Finals) )
    K
  • 原文地址:https://www.cnblogs.com/binhy0428/p/5127226.html
Copyright © 2011-2022 走看看