zoukankan      html  css  js  c++  java
  • python之字典方法

    1、Clear

    clear方法清除字典中所有的项。这是个原地操作,所以无返回值(或者说返回None)

    >>> d = {}
    >>> d['name']='SH'
    >>> d['other']='haha'
    >>> d
    {'name': 'SH', 'other': 'haha'}
    >>> return_value = d.clear()
    >>> d
    {}
    >>> print(return_value)
    None

    2、Copy

    cpoy方法返回一个具有相同键值对的新字典(这个方法实现的是浅复制,因为值本身就是相同的,而不是副本)。

    >>> x={'username':'admin','machines':['foo','bar','baz']}
    >>> y = x.copy()
    >>> y
    {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
    >>> y['username']='other'
    >>> y
    {'username': 'other', 'machines': ['foo', 'bar', 'baz']}
    >>> x
    {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
    >>> y['machines'].remove('bar')
    >>> y
    {'username': 'other', 'machines': ['foo', 'baz']}
    >>> x
    {'username': 'admin', 'machines': ['foo', 'baz']}

    可以看到,当在副本中替换值的时候,原始字典不受影响,但是,如果修改了某个值(原地修改,而不是替换),原始的字典也会改变,因为同样的值也存储在原字典中(就像上面例子中的machines列表一样)

    避免这个问题的一种方法就是一个使用深复制,复制其包含的所有值。可以使用copy模块的deepcopy函数来完成操作。

    >>> from copy import deepcopy
    >>> d = {}
    >>> d['names'] = ['Alfred','Bertrand']
    >>> c = d.copy()
    >>> dc = deepcopy(d)
    >>> c
    {'names': ['Alfred', 'Bertrand']}
    >>> dc
    {'names': ['Alfred', 'Bertrand']}
    >>> d['names'].append('Clive')
    >>> c
    {'names': ['Alfred', 'Bertrand', 'Clive']}
    >>> d
    {'names': ['Alfred', 'Bertrand', 'Clive']}
    >>> dc
    {'names': ['Alfred', 'Bertrand']}

    3、Formkeys

    fromkeys方法使用给定的键建立新的字典,每个键都对应一个默认的值None.

    >>> {}.fromkeys(['name','age'])
    {'name': None, 'age': None}

    刚才的例子中首先构造了一个空字典,然后调用它的fromkeys方法,建立另外一个词典有些多余,此外,您还可以直接在dict上面调用该方法,前面讲过,dict是所有字典的类型。

    >>> dict.fromkeys(['name','age'])
    {'name': None, 'age': None}

    如果不想使用None作为默认值,也可以自己提供默认值。

    >>> dict.fromkeys(['name','age'],'(unknown)')
    {'name': '(unknown)', 'age': '(unknown)'}

    4、Get

    get方法是个更宽松的访问字典项的方法。一般来说,如果试图访问字典中不存在的项时会出错。

    >>> d = {}
    >>> print(d['name'])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'name'

    而用get就不会:

    >>> print(d.get('name'))
    None

    5、Items

    items方法将字典所有的项以列表方式返回,列表中的每一项都表示为(键,值)对的形式。但是项在返回时并没有遵循特定的次序。

    >>> d={'title':'python','version':'3.6','spam':0}
    >>> d.items()
    dict_items([('title', 'python'), ('version', '3.6'), ('spam', 0)])

  • 相关阅读:
    记住我
    国米夺冠
    小谈“汉字转换成拼音(不带声调)”
    NLP资源共享盛宴
    文本分类资源和程序开源共享
    菜鸟进阶:C++实现Chisquare 特征词选择算法
    欢迎大家试用信息领域学科知识服务平台
    欢迎大家加入NLP,WEBIR,DATA Ming 的技术QQ群
    求两点之间所有路径的算法
    step by step 文本分类(一)
  • 原文地址:https://www.cnblogs.com/TaleG/p/8676783.html
Copyright © 2011-2022 走看看