python cookbook3第一章

  • 字典的运算
    • Dict文档相关

字典的运算

对字典的值执行计算操作,通常需要zip()函数先将键和值反转过来。比如:

gpm = {'ame':900,'chalice':600,'sccc':800,'eurus':850,
}print(max(zip(gpm.values(), gpm.keys()))) # output (900, 'ame')
print(min(zip(gpm.values(), gpm.keys()))) # output (600, 'chalice')print(sorted(zip(gpm.values(), gpm.keys()), reverse=True))
# output [(900, 'ame'), (850, 'eurus'), (800, 'sccc'), (600, 'chalice')]

能这么做的原因也是文档里写道,keys and values are iterated over in the same order,所以用zip()函数能重构原键值对,但同时需要注意zip()函数返回的是一个迭代器,只能访问一次。

如果你直接对字典执行运算,会发现仅仅作用于键,而不是值:

print(max(gpm)) # output sccc
print(min(gpm)) # output ame

Dict文档相关

因为发现gpm.keys()的数据类型是<class 'dict_keys'>gpm.values()也是对应的<class 'dict_values'>类型,于是就好奇去查了下文档,居然结果发现:

文档地址:https://docs.python.org/3.8/library/stdtypes.html#dict.keys
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

在python 3.7中,已经保证了python dict中元素的顺序和插入顺序是一致的,但后面介绍dict的时候,仍然将它当作无序来解释。所以我在上篇博客去看OrderedDict的源码是为了啥,哭了。

好了回归正题,keys()的定义:

Return a new view of the dictionary’s keys. See the documentation of view objects.

继续看这个view的定义:

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

是说这三个函数返回的都是对于字典里条目的动态视图,如果字典改变,这些视图也会随着改变

gpm = {'ame':900,'chalice':600,'sccc':800,'eurus':850,
}k = gpm.keys()
print(list(k)) # output ['ame', 'chalice', 'sccc', 'eurus']
del gpm['ame']
print(list(k)) # output ['chalice', 'sccc', 'eurus']

Dictionary views can be iterated over to yield their respective data, and support membership tests:

len(dictview):
 Return the number of entries in the dictionary.

iter(dictview):
 Return an iterator over the keys, values or items (represented as tuples of (key, value)) in the dictionary.

Keys and values are iterated over in insertion order. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()].

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

x in dictview  Return True if x is in the underlying dictionary’s keys, values or items (in the latter case, x should be a (key, value) tuple).

reversed(dictview) :
 Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.

Changed in version 3.8: Dictionary views are now reversible.

视图对象支持以上这些操作,比较重要的有iter()函数会返回一个迭代器,支持zip()函数的迭代操作iterators = [iter(it) for it in iterables]。但视图对象正在迭代的时候如果对字典有插入或者删除操作可能会报错RuntimeError或者不能迭代完整的条目。

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

最后一段也终于单独提到了键的视图,由于键的特性(唯一性和可哈希性),.keys()返回的对象是set-like的,如果所有的值是可哈希的,那么键值对也将拥有和键一样的两个特性,这时.items()返回的对象也将是set-like的。(由于值一般被认为不是唯一的,所以不是)对于所有的set-like对象,基础类collections.abc.Set里定义的所有操作都是适用的。(例如,==,-,<,^)

gpm = {'ame':900,'chalice':600,'sccc':800,'eurus':850,
}k = gpm.keys()
print(k-['ame'])     # output {'eurus', 'chalice', 'sccc'}
print(k-{'chalice'}) # output {'ame', 'eurus', 'sccc'}
print(k & {'ame'})   # output {'ame'}

python cookbook3笔记三相关推荐

  1. Python学习笔记三之编程练习:循环、迭代器与函数

    Python学习笔记三之编程练习 1. 编程第一步 # 求解斐波纳契数列 #/user/bin/python3#Fibonacci series:斐波那契数列 #两个元素的总和确定了下一个数 a,b= ...

  2. Python学习笔记三

    参考教程:廖雪峰官网https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000 一.函数的定 ...

  3. Python学习笔记三(文件操作、函数)

    一.文件处理 1.文件打开模式 打开文本的模式,默认添加t,需根据写入或读取编码情况添加encoding参数. r   只读模式,默认模式,文件必须存在,不能存在则报异常. w  只写模式,若文件不存 ...

  4. Python基础笔记(三) dict、set、函数

    一.字典 1.创建dict d = {'Adam': 95,'Lisa': 85,'Bart': 59 } 我们把名字称为key,对应的成绩称为value,dict就是通过 key 来查找 value ...

  5. 【懒懒的Python学习笔记三】

    在上一章中,我们学习了如何创建列表.访问列表元素和简单的列表排序.那么在本章中,我们将进一步学习如何遍历整个列表和对列表更多的操作. 一.遍历列表 我们经常需要遍历整个列表,对每个元素执行相同的操作, ...

  6. Python入门笔记(三)

    文章目录 第十二章 异常处理 12.1 常见异常 12.2 处理异常:try-- except 12.3 创建异常类型:raise语句 12.4 断言:assert 12.5 存储数据:json.du ...

  7. Python基础 笔记(三) 标识符、输入输出函数

    哈喽,大家好!今天来学习Python中的标识符和输入输出函数. 目录 一.标识符 二.输入函数 三.输出函数 四.print( )格式化输出 五.练习题 一.标识符 标识符:开发人员在程序中自定义的名 ...

  8. Python爬虫笔记三:微博登录(出师未捷身先死 长使英雄泪满襟)

    学习地址:https://www.cnblogs.com/xiao-apple36/articles/8768270.html 完整地址:https://www.cnblogs.com/xiao-ap ...

  9. python学习笔记三 pickle序列化

    import pickle f=file('asdf.txt','wb') pickle.dump(saved_info,f)#保存pickle信息 f.close() f=file(asdf.txt ...

最新文章

  1. 【转载】自然语言推理介绍
  2. legend3---lavarel中使用qq邮箱发送邮件
  3. 开关磁阻电机调速控制的仿真研究
  4. kotlin使用spring data jpa(一)
  5. Hibernate的fetch
  6. Recoll:Unix和Linux桌面的文本搜索工具
  7. UnicodeDecodeError(转)
  8. jquey-整屏滚动的制作过程
  9. 译稿:软件工程师不可不知的10个概念
  10. 蒙特卡洛树搜索_Query 理解和语义召回在知乎搜索中的应用
  11. WCF编程]WCF使用Net.tcp绑定时候出现错误:元数据包含无法解析的引用
  12. 芝麻HTTP:TensorFlow LSTM MNIST分类
  13. 流媒体压力测试工具—推拉流
  14. 工作流-Activiti7-基础讲解
  15. 不用爬虫,也能写一个聚合搜索引擎
  16. Enscape for SketchUp 室外日夜景照明设置技巧
  17. “三权分立”模型的概述
  18. 做网站需要哪些费用?(维护方面)
  19. selenium录屏python_Selenium实现录屏的一种方法
  20. 安卓应用开发 MyWeChat(二)

热门文章

  1. 语音的基本概念(理解senone时看的较好的文章)
  2. 技能提升之keil5 调用外部编辑器总结
  3. unity Invoke
  4. 一些在线工具集(图形处理、开发工具集、cdn服务)
  5. 位域结构体的理解和使用(内含单片机驱动开发小技巧)
  6. [Android] Eclipse Android中设置模拟器屏幕大小几种方法
  7. EXCEL应用操作(一)函数
  8. 关于mid函数的一些用法
  9. 关于mvvm的ComboBox绑定SelectedValue值不正确问题
  10. JavaScript实现屏幕录像