zoukankan      html  css  js  c++  java
  • 《Python核心编程》第二版第186页第七章练习

    7-1.
    字典方法。哪个字典方法可以用来把两个字典合并到一起。
    【答案】
    dict.update(dict2)
    将字典dict2的键-值对添加到字典dict

    7-2.
    字典的键。我们知道字典的值可以是任意的Python对象,那字典的键又如何呢?请试着将除数字和字符串意外的其他不同类型的对象作为字典的键,看看哪些类型可以,哪些不行。对那些不能作为字典的键的对象类型,你认为是什么原因呢?
    【答案】
    Python对象:
    可哈希对象(不变类型)---数字,字符串和元组(但要加以限制)
    不可哈希对象(可变类型)--列表,字典,集合
    需要注意的是:值相等的数字代表同一个键,元组作为键时,其元素必须是可哈希的。
    内建函数hash()可以判断某个对象是否可以做一个字典的键,如果非可哈希类型作为参数传递给hash()方法,会产生TypeError错误,否则会产生hash值,整数。
    >>> hash(1)
    1
    >>> hash('a')
    -468864544
    >>> hash([1,2])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    >>> hash({1:2,})
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'dict'
    >>> hash(set('abc'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'set'
    >>> hash(('abc'))
    -1600925533
    >>> hash(1.0)
    1
    >>> hash(frozenset('abc'))
    -114069471
    >>>
    >>> hash(((1, 3, 9)))
    1140186820
    >>> hash(((1, 3, '9'), (1, 2)))
    1944127872
    >>> hash(((1, 3, '9'),[1,2], (1, 2)))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    >>>

  • 相关阅读:
    状态模式
    适配器模式
    观察者模式
    浮点数在内存中的存储方式
    建造者模式
    外观模式
    模版方法模式
    原型模式
    Python 学习笔记6 变量-元组
    Python 学习笔记5 变量-列表
  • 原文地址:https://www.cnblogs.com/balian/p/2077383.html
Copyright © 2011-2022 走看看