学习笔记之Python

Source Codehtml

Welcome to Python.orgpython

3.6.3rc1 Documentationlinux

PEP 8 -- Style Guide for Python Code | Python.orggit

Python_百度百科程序员

  • https://baike.baidu.com/item/Python/407313?fr=aladdin#reference-[12]-21087-wrap
  • 自从20世纪90年代初Python语言诞生至今,它已被逐渐普遍应用于系统管理任务的处理和Web编程。
  • Python是彻底面向对象的语言。函数、模块、数字、字符串都是对象。而且彻底支持继承、重载、派生、多继承,有益于加强源代码的复用性。Python支持重载运算符和动态类型。
  • Python容许像数学的经常使用写法那样连着写两个比较运行符。好比a < b < c与a < b and b < c等价。C++的结果与Python不同,首先它会先计算a < b,根据二者的大小得到0或者1两个值之一,而后再与c进行比较。
  • Python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数,而由Python标准库提供了系统管理、网络通讯、文本处理、数据库接口、图形系统、XML处理等额外的功能。

学习笔记之Python IDE ( Anaconda / PyCharm ) - 浩然119 - 博客园github

学习笔记之Python 3web

面试总结之Python - 浩然119 - 博客园面试

学习笔记之盘一盘 Python 系列 1 & 2 - 入门篇 - 浩然119 - 博客园正则表达式

学习笔记之Python爬虫 - 浩然119 - 博客园算法

学习笔记之Django - 浩然119 - 博客园

Python3 教程 | 菜鸟教程

Python 入门指南 — Python tutorial 3.6.0 documentation

在 Windows 上使用 Python 进行开发 - Windows apps | Microsoft Docs

网络课程 python 网络教育-百度传课

Python Example

一文总结学习 Python 的 14 张思惟导图 - 人工智能与大数据技术

  • https://mp.weixin.qq.com/s/yuxqP0cNsUgYnfLlStEQ5Q
  • https://woaielf.github.io/2017/06/13/python3-all/
  • 本文主要涵盖了 Python 编程的核心知识(暂不包括标准库及第三方库,后续会发布相应专题的文章)。
  • 第1张图
    • 基础知识图一包括了基本规则、Python语言特色、计算机语言、如何运行Python、变量赋值五个方面,辅助你快速掌握Python编程的基底知识。
  • 第2张图
    • 基础知识图二包含了模块结构、布局、IO编程流程、标识符、Python对象、内存管理、动态类型六大模块,两张基础知识导图能够帮助你区域化了解Python的组成部分及基本操做。
  • 第3张图
    • 学习Python少不了对数据的了解,这张图整理了数据类型的分类、做用、空值、标准数据、if语句等等模块。
  • 第4张图
    • 这张图整理了序列的有序排列、标准操做符与序列类型操做符的重点知识,以及可操做性的BIF。
  • 第5张图
    • 字符串是个比较庞大而精细的部分,接着上图的BIF可分为标准类型、序列类型、字符串类型,字符串可分为五种操做符类型,此图还整理了序列的独特特性以及编码问题,能够说很详细了。
  • 第6张图
    • 关于列表|元素,首先说拷贝问题,分深浅拷贝两种形式。tuple的内建函数、特殊特性与list的操做符、内建函数是重点部分。
  • 第7张图
    • 这张图主要整理了字典|集合中set、dict的功能、分类、BIF、操做问题。
  • 第8张图
    • 条件|循环包含生成器、迭代器、列表解析的使用、拓展,相关BIF、if语句循环控制也可以快速掌握重点。
  • 第9张图
    • 关于文件对象内建方法、内建函数、内建属性都有具体内容,文件迭代的运用,标准文件对象如何输入输出以及分隔符的运用都在导图中详细标明。
  • 第10张图
    • 错误|异常这张图的点介绍了如何调试、处理异常状况。
  • 第11张图
    • 函数一介绍了函数概述,注意vs函数的引用、调用,装饰器的定义、“堆叠”。参数具备本身的完整语法以及本身的传递方式。
  • 第12张图
    • 函数二图整理了递归函数、返回(回调)函数、变量做用域、偏函数、函数式编程、匿名函数、高阶函数BIF的详细介绍。
  • 第13张图
    • 这张图的重点是模块的标准区域、名称空间以及模块的做用域(三种变量的运用)。
  • 第14张图
    • 最后一张图整理了面向对象编程,弄清楚面向对象的基本概念,继承与多态、结构组织以及对象的性质、访问限制等重点,对于python就算是入门了。

学习Python必备的8本书 - Python编程

Python 语法速览与实战清单 - Python编程

Python 教程:从零到大师 - Python编程

Python三十年技术演变史


BASIC

Python 字符串拼接总结 - Python编程

Python字符串用法大全

Python字符串处理的8招秘籍

如何优雅的操做Python字典 - 程序员大咖

干货|理解Python列表和元组

图解 Python 函数


ADVANCE

5张图理解Python中的浅拷贝与深拷贝

Python 程序员如何防止数据被修改?

Python 进阶:全面解读高级特性之切片

迭代器与生成器

Python 迭代器与生成器 - Python编程

  • https://mp.weixin.qq.com/s/cT0vqLAvqOc5FNnx6Iu_iw
  • http://www.langzi.fun/%E8%BF%AD%E4%BB%A3%E5%99%A8%E4%B8%8E%E7%94%9F%E6%88%90%E5%99%A8.html

Python 迭代器和 C++ 迭代器最大的不一样

带你完全搞懂Python生成器

完全理解Python中的yield

模块

深刻探讨Python的import机制:实现远程导入模块 | CSDN博文精选

Python Logging 模块彻底解读

四种高性能数据类型,Python collections助你优化代码、简洁任务

IO / FILE

Python 数据形态及IO操做

Python处理CSV、JSON和XML数据的简便方法

错误和异常

学习笔记之Python Debug ( pdb ) - 浩然119 - 博客园

一文教你读懂 Python 中的异常信息

面向对象

Python 面向对象编程

  • https://mp.weixin.qq.com/s/IFRloykz9Nnb3N94CQpieg
  • http://www.langzi.fun/Python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B.html
  • 面向过程编程
  • 面向对象编程
  • 类的基本用法
  • 类与实例
  • 调用类的三种方法
    • 实例方法
    • 静态方法
    • 类方法
  • 类的特性
    • 封装
    • 继承
    • 多态
  • 魔法方法
    • __doc__
      • 说明性文档和信息。Python自建,无需自定义。  
    • __init__
      • 实例化方法,经过类建立实例时,自动触发执行。  
    • __module__ / __class__
      • module 表示当前操做的对象在属于哪一个模块。
      • class 表示当前操做的对象属于哪一个类。
      • 这二者也是Python内建,无需自定义。  
    • __del__
      • 析构方法,当对象在内存中被释放时,自动触发此方法。
      • 注:此方法通常无须自定义,由于Python自带内存分配和释放机制,除非你须要在释放的时候指定作一些动做。析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
    • __call__
      • 若是为一个类编写了该方法,那么在该类的实例后面加括号,可会调用这个方法。
      • 注:构造方法的执行是由类加括号执行的,即:对象 = 类名(),而对于call() 方法,是由对象后加括号触发的,即:对象() 或者 类()()
      • 能够用Python内建的callable()函数进行测试,判断一个对象是否能够被执行。
    • __dict__
      • 列出类或对象中的全部成员!很是重要和有用的一个属性,Python自建,无需用户本身定义。  
    • __str__
      • 若是一个类中定义了str()方法,那么在打印对象时,默认输出该方法的返回值。这也是一个很是重要的方法,须要用户本身定义。  
    • __getitem__ / __setitem__ / __delitem__
      • 取值、赋值、删除这“三剑客”的套路,在Python中,咱们已经见过不少次了,好比前面的@property装饰器。
      • Python中,标识符后面加圆括号,一般表明执行或调用方法的意思。而在标识符后面加中括号[],一般表明取值的意思。Python设计了getitem()、setitem()、delitem()这三个特殊成员,用于执行与中括号有关的动做。它们分别表示取值、赋值、删除数据。
      • 若是有一个类同时定义了这三个魔法方法,那么这个类的实例的行为看起来就像一个字典同样
    • __iter__
      • 这是迭代器方法!列表、字典、元组之因此能够进行for循环,是由于其内部定义了 iter()这个方法。若是用户想让自定义的类的对象能够被迭代,那么就须要在类中定义这个方法,而且让该方法的返回值是一个可迭代的对象。当在代码中利用for循环遍历对象时,就会调用类的这个iter()方法。  
    • __len__
      • 在Python中,若是你调用内置的len()函数试图获取一个对象的长度,在后台,实际上是去调用该对象的len()方法
      • Python的list、dict、str等内置数据类型都实现了该方法,可是你自定义的类要实现len方法须要好好设计。
    • __repr__
      • 这个方法的做用和str()很像,二者的区别是str()返回用户看到的字符串,而repr()返回程序开发者看到的字符串,也就是说,repr()是为调试服务的。一般二者代码同样。
    • __add__ / __sub__ / __mul__ / __div__ / __mod__ / __pow__
      • 这些都是算术运算方法,须要你本身为类设计具体运算代码。有些Python内置数据类型,好比int就带有这些方法。Python支持运算符的重载,也就是重写。  
    • __cmp__
      • 比较运算
    • __author__
      • 做者信息  
    • __slots__
      • Python做为一种动态语言,能够在类定义完成和实例化后,给类或者对象继续添加随意个数或者任意类型的变量或方法,这是动态语言的特性。
      • 可是!若是我想限制实例能够添加的变量怎么办?可使slots限制实例的变量,好比,只容许Foo的实例添加name和age属性。
      • 须要提醒的是,slots定义的属性仅对当前类的实例起做用,对继承了它的子类是不起做用的。想一想也是这个道理,若是你继承一个父类,却莫名其妙发现有些变量没法定义,那不是大问题么?若是非要子类也被限制,除非在子类中也定义slots,这样,子类实例容许定义的属性就是自身的slots加上父类的slots。
  • 成员保护与访问机制
    • 私有成员
    • 使用get-set-del方法操做私有成员
  • Propety装饰器
  • 经常使用的调用方法
  • 使用装饰器
  • 更加减半的使用property()函数

简单理解python面向对象及装饰器

  • https://mp.weixin.qq.com/s/jaoMUy5okkMZ9QOYK-og1Q
  • 1、类
  • 2、继承
  • 3、多态
  • 4、封装
  • 5、装饰器
  • 6、闭包
    • @property:@property把类方法改为类属性,实现存取器
    • @classmethod:能够用来定义类方法(不用实例就能够调用)
    • @staticmethod:主要是方便将外部函数集成到类体中,而且用staticmethod包装的方法能够内部调用,也能够经过类访问或类实例化访问。

如何理解 Python 中的面向对象编程?

没看完这11 条,别说你精通 Python 装饰器

Python中的元编程:一个关于修饰器和元类的简单教程

多线程

浅谈 Python 中的多线程 - Python编程

  • https://mp.weixin.qq.com/s/7dLKlCUumx9NS-Zmv8iSvA

理解python多线程和多进程

深刻理解python多线程和多进程

入门 | 三行Python代码,让数据预处理速度提升2到6倍

编码

一文透彻掌握 Python 编码问题

一图看懂 Python 2 / Python 3 编码 | CSDN 博文精选


PYTHONIC STYLE

STYLE GUIDE

学习笔记之Python最简编码规范 - 浩然119 - 博客园

代码整洁之道-编写 Pythonic 代码

Python 编码风格指南

Python 简洁编码之道

18式优雅你的Python

改善Python程序的91个建议 - Python编程

符合语言习惯的 Python 优雅编程技巧 - 超级数学建模

优雅编写Python3的62个小贴士

TIPS

@Python 程序员,如何最大化提高编码效率?

这些Python代码技巧,你确定还不知道

wtfPython—Python中一些奇妙的代码

15个Pythonic的代码示例

7个案例15分钟让你了解Python套路

Python带我飞:50个有趣而又不为人知的Python特性

Python中实用却不常见的小技巧

Python 开发中有哪些高级技巧?

18 个 Python 高效编程技巧

10招玩转Python

学Python,从列表推导到zip()函数,这五种技巧应知应会

10 个鲜为人知的Python冷知识

Python的高级特征你知多少

26个Python实用技巧

Python 有哪些不同的技巧

即学即用的30段Python实用代码

每30秒学会一个Python小技巧

Python的 5 种高级用法

Python 的 20 个操做

Python技巧小贴士

Python 十大语法

20 个 Python 技巧


BEST PRACTICE

Python编写循环的两个建议 | 鹅厂实战

  • https://mp.weixin.qq.com/s/Vh2pwcI_PjtoagaVmz2dHw
  • https://github.com/piglei/one-python-craftsman
  • 什么是“地道”的循环?
    • enumerate() 所表明的编程思路
  • 建议1:使用函数修饰被迭代对象来优化循环
    1. 使用 product 扁平化多层嵌套循环
    2. 使用 islice 实现循环内隔行处理
    3. 使用 takewhile 替代 break 语句
    4. 使用生成器编写本身的修饰函数
  • 建议2:按职责拆解循环体内复杂代码块
    • 复杂循环体如何应对新需求
    • 使用生成器函数解耦循环体
  • 总结
    • 使用函数修饰被循环对象自己,能够改善循环体内的代码
    • itertools 里面有不少工具函数均可以用来改善循环
    • 使用生成器函数能够轻松定义本身的修饰函数
    • 循环内部,是一个极易发生“代码膨胀”的场地
    • 请使用生成器函数将循环内不一样职责的代码块解耦出来,得到更好的灵活性

8个Python高效数据分析的技巧

7 个 Python 特殊技巧,有效提高数分效率!

使用类型注解让 Python 代码更易读

分享8点有用的Python编程建议

  • https://mp.weixin.qq.com/s/LtOUArQWA3BIdqFBjMkYcA
  • 项目文件事先作好归档
  • 永远不要手动修改源数据而且作好备份
  • 作好路径的正确配置
  • 代码必要的地方作好备注与说明
  • 加速你的Python循环代码
  • 可视化你的循环代码进度
  • 使用高效的异常捕获工具
  • 要多考虑代码健壮性

为何Python不用设计模式?

动态类型一时爽,代码重构火葬场?

Python 10大谬论

Python 初学者常犯的5个错误,布尔型竟是整型的子类

Python 常见的17个错误分析

运行速度

为何Python这么慢? - Python编程

一行代码让 Python 的运行速度提升100倍

24式加速你的Python

内存

Python技巧 | 一行代码减小一半内存占用

如何下降 Python 的内存消耗量?

Python 内存分配时的小秘密

资源库工具

Python算法实现资源汇总

那些有趣/用的 Python 库

140种Python标准库、第三方库和外部工具都有了

介绍几款 Python 类型检查工具

Python中的两个测试工具

Python 中更优雅的日志记录方案

如何编写完美的 Python 命令行程序?


APPLICATION

用 Python 打包本身的库到 PYPI

用 Python 写一个安卓 APP

用Python把Linux命令写一遍

“堆”的 Python 实现与应用总结

如何用 Python 快速开发一个区块链数据结构?

一文读懂Python复杂网络分析库networkx | CSDN博文精选

开发必学的验证码,教你从零写一个验证码

万字干货 | Python后台开发的高并发场景优化解决方案

Python实现五子棋人机对战 | CSDN博文精选

用 Python 偷偷抓取了她的行踪

谁偷偷删了你的微信?别慌!Python 帮你都揪出来了

AI

不足 20 行 Python 代码,高效实现 k-means 均值聚类算法!

使用Python进行机器学习的假设检验(附连接&代码)

Python 天然语言处理:轻松上手文本分类

用 Python 自制序列标注平台

用 Python 实现英文单词纠错功能

利用 50 行 Python 代码构建一个在线文本生成器!

如何建立一个百分百懂你的产品推荐系统 | 深度教程(附代码详解)

如何经过 Python 和 OpenCV 实现目标数量监控?

DATA SCIENCE

【实战】使用 Python 分析 14 亿条数据

用 Python 绘制污染物玫瑰图

用 Python 测算气象预报的空报率与漏报率

FILE

利用 tornado 实现表格文件预览

Python 处理分析 128 张 Excel 表格竟不到3秒?| 附数据集

我用Python作了一份PDF报告 - Python编程

将Python字符串生成PDF

用 Python 操做 Word 文档

爬虫分析

基于豆瓣影评数据的完整文本分析

如何经过 Python 分析中国演员排名?

Python 爬取 3000 部电影,最具人气烂片排行榜出炉!

基于微博数据的人物性格分类系统

基于词典和弱标注信息的电影评论情感分析系统

分析了16年的福利彩票记录,原来能够用Python这么买彩票

Python 分析国庆热门旅游景点

用 Python 总结分析男篮世界杯

用 Python 分析各国人口性别比例

用Python分析全国高等教育分布状况

Python 分析中国城市夜间灯光数据

教你如何用Python自动下载抖音小姐姐

用 Python 全自动下载抖音视频


《Python入门必备指南》之如何系统地自学 Python?_腾讯课堂

  • https://ke.qq.com/course/217064
  • 经过实例知道下list,dict实际使用中一些技巧
  • 了解web编程的学习线路图,知识网络
  • get(key[, default])
    • https://docs.python.org/3/library/stdtypes.html?highlight=get#dict.get
    • Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError
  • sorted(iterable, *, key=None, reverse=False)
    • https://docs.python.org/3/library/functions.html?highlight=sorted#sorted
    • Return a new sorted list from the items in iterable.
  • items()
    • https://docs.python.org/3/library/stdtypes.html?highlight=items#dict.items
    • Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.
  • 4.7.5. Lambda Expressions
    • https://docs.python.org/3/tutorial/controlflow.html?highlight=lambda#lambda-expressions
    • Small anonymous functions can be created with the lambda keyword.
 1 #!/usr/bin/python3
 2 
 3 res = {}
 4 with open('demo.txt') as f:
 5     for ch in f.read().replace(' ', ''):
 6         res[ch] = res.get(ch, 0) + 1
 7 
 8 # lambda x[1] stands for value in dictionary, x[0] stands for key in dictionary
 9 for char, num in sorted(res.items(), key=lambda x: x[1], reverse=True)[:3]:
10     print('char %s count is %d' % (char, num))
View Code

深刻浅出带你学Python冲击年薪30万【马哥教育】_腾讯课堂

  • https://ke.qq.com/course/134017
  • Python哲学
    • import this
  • Python使用引用计数记录全部变量的引用数
    • 当变量引用数变为0,它就能够被垃圾回收GC。
    • 计数增长:赋值给其余变量就增长引用计数。E.g. x = 3; y = x;
    • 计数减小:
      • 函数运行结束时,局部变量就被自动销毁,对象引用计数减小;
      • 变量被赋值给其余变量。x = 3; y = x; x = 4;

【Python入门只需20分钟】从安装到数据抓取、存储原来这么简单 - 旺旺笔记 - 博客园

  • https://www.cnblogs.com/zhaww/p/9517514.html

What's package and module ?

  • Python 提供了一个办法,把这些定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块。模块是一个包含全部你定义的函数和变量的文件,其后缀名是.py。模块能够被别的程序引入,以使用该模块中的函数等功能。这也是使用 python 标准库的方法。
  • 包是一种管理 Python 模块命名空间的形式,采用"点模块名称"。在导入一个包的时候,Python 会根据 sys.path 中的目录来寻找这个包中包含的子目录。目录只有包含一个叫作 __init__.py 的文件才会被认做是一个包,主要是为了不一些滥俗的名字(好比叫作 string)不当心的影响搜索路径中的有效模块。

Abstract base class v.s. Interface ?

如何多行字符串拼接?

 1 # -*- coding: utf-8 -*-
 2 """
 3 @author: Hao
 4 """
 5 
 6 start_timestamp = "2018-01-01 00:00:00"
 7 end_timestamp = "2018-01-02 00:00:00"
 8 
 9 # =============================================================================
10 # SELECT "timestamp", col1
11 # FROM tbl
12 # WHERE "timestamp" >= '2018-01-01 00:00:00' AND "timestamp" <= '2018-01-02 00:00:00' 
13 # ORDER BY "timestamp" ASC
14 # =============================================================================
15 query = """
16     SELECT "timestamp", col1
17     FROM tbl
18     WHERE "timestamp" >= '"""             \
19     + start_timestamp +                 \
20     """' AND "timestamp" <= '"""        \
21     + end_timestamp +                   \
22     """' 
23     ORDER BY "timestamp" ASC
24     """
25 
26 print(query)
27 
28 # =============================================================================
29 # SELECT "timestamp", col1
30 # FROM tbl
31 # WHERE "timestamp" >= '2018-01-01 00:00:00' AND "timestamp" <= '2018-01-02 00:00:00' 
32 # ORDER BY "timestamp" ASC
33 # =============================================================================
34 query = ("""
35     SELECT "timestamp", col1
36     FROM tbl
37     WHERE "timestamp" >= '"""       
38     + start_timestamp +                 
39     """' AND "timestamp" <= '"""        
40     + end_timestamp +                   
41     """' 
42     ORDER BY "timestamp" ASC
43     """)
44 
45 print(query)
View Code

Comparisons

  • 6. Expressions — Python 3.7.4 documentation
    • https://docs.python.org/3/reference/expressions.html#comparisons
    • Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like c have the interpretation that is conventional in mathematics
    • Comparisons can be chained arbitrarily, e.g., <= z is equivalent to and <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when y is found to be false).

Conditional Expressions

  • 6. Expressions — Python 3.7.0 documentation
    • https://docs.python.org/3/reference/expressions.html?highlight=conditional%20expressions#conditional-expressions
    • x = 1 if y == 1 else 0
    • 注意Python中没有三元运算符 y == 1 ? 1 : 0
  • 1 PEP 308: Conditional Expressions
    • https://docs.python.org/2.5/whatsnew/pep-308.html

How to display a decimal in scientific notation ?

  • '{:.2e}'.format(0.456) = '4.56e-01'
  • '{:.2f}'.format(0.456) = '0.46'
  • python - Display a decimal in scientific notation - Stack Overflow
    • https://stackoverflow.com/questions/6913532/display-a-decimal-in-scientific-notation

What's the infinity number ?

zip

  • https://docs.python.org/3/library/2to3.html?highlight=zip#2to3fixer-zip
  • Wraps zip() usage in a list call. This is disabled when from future_builtins import zip appears. 

How to convert dictionary to list ?

  • Converting Python Dictionary to List - Stack Overflow
    • https://stackoverflow.com/questions/1679384/converting-python-dictionary-to-list
  • 4. Built-in Types — Python 3.6.6rc1 documentation
    • https://docs.python.org/3/library/stdtypes.html?highlight=items#dict.items
    • https://docs.python.org/3/library/stdtypes.html?highlight=items#dictionary-view-objects

How to convert list to string ?

  • stest = str(['test1', 'test2', 'test3']).strip('[]')
  • 4. Built-in Types — Python 3.6.6rc1 documentation
    • https://docs.python.org/3/library/stdtypes.html?highlight=str#text-sequence-type-str
    • https://docs.python.org/3/library/stdtypes.html?highlight=str#str.strip
  • python - TypeError: cannot concatenate 'str' and 'list' objects in email - Stack Overflow
    • https://stackoverflow.com/questions/26521899/typeerror-cannot-concatenate-str-and-list-objects-in-email

How to convert list to tuple ?

How to check if a list contains elements of another list ?

How to check if substring exists ?

  • if "substring" in test_string:
  • if s.startswith(("a", "b")):
  • 6. Expressions — Python 3.7.2rc1 documentation - Membership test operations
    • https://docs.python.org/3/reference/expressions.html#membership-test-details
  • Built-in Types — Python 3.7.2rc1 documentation
    • str.startswith(prefix[, start[, end]])
    • Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
  • Does Python have a string 'contains' substring method? - Stack Overflow
    • https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method
    • if "blah" not in somestring: 

How to replace characters / substring in a string ?

  • 'www.example.com'.strip('cmowz.')
  • str.replace('html', 'log')
  • Pay attention that strip will only remove the leading and trailing characters.
  • Built-in Types — Python 3.7.1 documentation - str.strip([chars])
    • https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip
    • Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
  • str.replace(old, new[, count])
    • https://docs.python.org/3/library/stdtypes.html?highlight=replace#str.replace
    • Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Two types usage of for loop ?

  • python - "for loop" with two variables? - Stack Overflow
    • https://stackoverflow.com/questions/18648626/for-loop-with-two-variables

datetime operation

  • Get date of the datetime instance
    • 8.1. datetime — Basic date and time types — Python 3.6.6rc1 documentation
      • https://docs.python.org/3/library/datetime.html#datetime.date
  • timedelta Objects - datetime — Basic date and time types — Python 3.7.2 documentation
    • https://docs.python.org/3/library/datetime.html#timedelta-objects
    • class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
  • Python datetime to string without microsecond component - Stack Overflow
    • https://stackoverflow.com/questions/7999935/python-datetime-to-string-without-microsecond-component
    • 8.1. datetime — Basic date and time types — Python 3.3.7 documentation
      • https://docs.python.org/3.3/library/datetime.html#datetime.datetime.strftime
  • How to increment the day in datetime? Python - Stack Overflow
    • https://stackoverflow.com/questions/3240458/how-to-increment-the-day-in-datetime-python
    • date += datetime.timedelta(days=1)

How to find the min value in dictionary ?

  • min(d.items(), key=lambda x: x[1])
  • min(d.items(), key=d.get)
  • min(d.values())
  • min(d.keys())
  • python - Get the key corresponding to the minimum value within a dictionary - Stack Overflow
    • https://stackoverflow.com/questions/3282823/get-the-key-corresponding-to-the-minimum-value-within-a-dictionary
    • min(d, key=d.get)
  • python - Getting key with maximum value in dictionary? - Stack Overflow
    • https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary
  • 2. Built-in Functions — Python 3.7.0 documentation
    • https://docs.python.org/3/library/functions.html?highlight=min#min
    • https://docs.python.org/3/library/stdtypes.html?highlight=dictionary#dict.get
  • Python3 min() 函数 | 菜鸟教程
    • http://www.runoob.com/python3/python3-func-number-min.html
  • Python3 字典 get() 方法 | 菜鸟教程
    • http://www.runoob.com/python3/python3-att-dictionary-get.html

How to check if dictionary/list/string/tuple is empty ?

  • PEP 8 -- Style Guide for Python Code | Python.org
    • https://www.python.org/dev/peps/pep-0008/
    • For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
    • Yes: if not seq: / if seq:
    • No: if len(seq): / if not len(seq):
  • Python: Checking if a 'Dictionary' is empty doesn't seem to work - Stack Overflow
    • https://stackoverflow.com/questions/23177439/python-checking-if-a-dictionary-is-empty-doesnt-seem-to-work
  • python - How do I check if a list is empty? - Stack Overflow
    • https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty

How to print lists ?

  • Print lists in Python (4 Different Ways) - GeeksforGeeks
  • https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/
  1 # -*- coding: utf-8 -*-
  2 """
  3 Created on Thu Nov 22 11:05:55 2018
  4 
  5 @author: h.tang
  6 """
  7 
  8 # using for loop
  9 a = [1, 2, 3, 4, 5]
 10 
 11 # =============================================================================
 12 # 1. Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one uisng a for loop,
 13 # this is the standard practice of doing it.
 14 # =============================================================================
 15 #1
 16 #2
 17 #3
 18 #4
 19 #5
 20 #1 2 3 4 5
 21 
 22 # printing the list using loop
 23 for x in range(len(a)):
 24     print a[x]
 25 
 26 for x in range(len(a)):
 27     print a[x],
 28 
 29 # =============================================================================
 30 # 2. Without using loops: * symbol is use to print the list elements in a single line with space.
 31 # To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.
 32 # =============================================================================
 33 # Python program to print list
 34 # without using loop
 35 
 36 a = [1, 2, 3, 4, 5]
 37 
 38 #1 2 3 4 5
 39 #printing lists separated by commas
 40 #1, 2, 3, 4, 5
 41 #printing lists in new line
 42 #1
 43 #2
 44 #3
 45 #4
 46 #5
 47 
 48 # printing the list using * operator separated
 49 # by space
 50 print(*a)
 51 
 52 # printing the list using * and sep operator
 53 print("printing lists separated by commas")
 54 
 55 print(*a, sep = ", ")
 56 
 57 # print in new line
 58 print("printing lists in new line")
 59 
 60 print(*a, sep = "\n")
 61 
 62 # =============================================================================
 63 # 3. Convert a list to a string for display : If it is a list of strings we can simply join them using join() function,
 64 # but if the list contains integers then convert it into string and then use join() function to join them to a string and print the string.
 65 # =============================================================================
 66 # Python program to print list
 67 # by Converting a list to a
 68 # string for display
 69 a =["Geeks", "for", "Geeks"]
 70 
 71 #Geeks for Geeks
 72 #1, 2, 3, 4, 5
 73 
 74 # print the list using join function()
 75 print(' '.join(a))
 76 
 77 # print the list by converting a list of
 78 # integers to string
 79 a = [1, 2, 3, 4, 5]
 80 
 81 print str(a)[1:-1]
 82 
 83 # =============================================================================
 84 # 4. Using map : Use map() to convert each item in the list to a string if list is not a string, and then join them
 85 # =============================================================================
 86 # Python program to print list
 87 # print the list by converting a list of
 88 # integers to string using map
 89 a = [1, 2, 3, 4, 5]
 90 #1 2 3 4 5
 91 #in new line
 92 #1
 93 #2
 94 #3
 95 #4
 96 #5
 97 print(' '.join(map(str, a)))
 98 
 99 print"in new line"
100 print('\n'.join(map(str, a)))
View Code

How to create and initialise list with repeated N times ?

  • x = [5]
  • print(x * 5)  // [5, 5, 5, 5, 5]
  • print([x] * 5) // [[5], [5], [5], [5], [5]]
  • Create List of Single Item Repeated n Times in Python - Stack Overflow
    • https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python/3459131
    • [e] * n
  • [ [ 1 for x in range(n) ] for x in range(m) ]

How to remove duplicates in lists ?

  • python - Removing duplicates in lists - Stack Overflow
    • https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists
    • list(set(t))
  • 5. Data Structures — Python 3.7.0 documentation
    • https://docs.python.org/3/tutorial/datastructures.html#sets
    • Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

How to print dictionary / list on multiple lines with pprint?

What's namedtuple ?

  • collections — Container datatypes — Python 3.8.0 documentation
    • https://docs.python.org/3/library/collections.html#collections.namedtuple
    • collections.namedtuple(typenamefield_names*rename=Falsedefaults=Nonemodule=None)
    • Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

How to check type of object ?

How to check if file exists ?

  • os.path — Common pathname manipulations — Python 3.7.2 documentation
    • https://docs.python.org/3/library/os.path.html?highlight=isfile#os.path.isfile
    • os.path.isfile(path)
    • Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
  • Python: Check if a File or Directory Exists
    • https://stackabuse.com/python-check-if-a-file-or-directory-exists/
    • Checking if a File Exists
      • os.path.isfile()
    • Checking if a Directory Exists
      • os.path.isdir()
    • Checking if Either Exist
      • os.path.exists()

How to iterate directory for files ?

1 import os
2 
3 root = '.'
4 
5 for path, subdirs, files in os.walk(root):
6     for name in files:
7         if name.endswith('.json'):
8             filename = os.path.join(path, name)
9             print(filename) # '.\path\test.json'
View Code

How to input and output file ?

 1 with open( filename, 'r' ) as f:
 2     for line in f:
 3         print(line, end='')
 4        
 5 import json        
 6 with open( filename, 'w' ) as f:
 7     json.dump(text, f)                
 8     
 9 with open(filename, 'r') as f:
10     x = json.load(f)
View Code

How to use try ... except ... finally statement for exception ?

How to define custom exception ?

How to use Regular Expression 正则表达式 ?

 1 import re
 2 
 3 filename = 'test.log'
 4 pattern = re.compile('FinishedMessage from (?P<truck>.*):.*d=(?P<dump>.*)')
 5 dumps = {}
 6 
 7 with open( filename, 'r' ) as f:
 8     for line in f:
 9         print(line)
10 
11         match = re.search(pattern, line)
12         print(match)
13 
14         if match:
15             print(match.group(0))
16             print(match.group(1))
17             print(match.group(2))
18             print(match.groupdict())
19             print(match.groupdict()['truck'])
20             print(match.groupdict()['dump'])
21 
22             dump = match.groupdict()['dump']
23 
24             if dump not in dumps:
25                 dumps[ dump ] = [ match.groupdict()['truck'] ]
26             else:
27                 dumps[ dump ].append(match.groupdict()['truck'])
28         print()
29 
30 import pprint
31 pprint.pprint(dumps, width=1)
32 
33 # =============================================================================
34 # [1] FinishedMessage from t1: group=[1] d=D1
35 # 
36 # <re.Match object; span=(4, 43), match='FinishedMessage from t1: group=[1] d=D1'>
37 # FinishedMessage from t1: group=[1] d=D1
38 # t1
39 # D1
40 # {'truck': 't1', 'dump': 'D1'}
41 # t1
42 # D1
43 # 
44 # [2] FinishedMessage from t2: group=[2] d=D2
45 # 
46 # <re.Match object; span=(4, 43), match='FinishedMessage from t2: group=[2] d=D2'>
47 # FinishedMessage from t2: group=[2] d=D2
48 # t2
49 # D2
50 # {'truck': 't2', 'dump': 'D2'}
51 # t2
52 # D2
53 # 
54 # [3] FinishedMessage from t3: group=[3] d=D2
55 # <re.Match object; span=(4, 43), match='FinishedMessage from t3: group=[3] d=D2'>
56 # FinishedMessage from t3: group=[3] d=D2
57 # t3
58 # D2
59 # {'truck': 't3', 'dump': 'D2'}
60 # t3
61 # D2
62 # 
63 # {'D1': ['t1'],
64 #  'D2': ['t2',
65 #         't3']}
66 # =============================================================================
View Code

How to use logging ?

  • Logging HOWTO — Python 3.7.0 documentation
    • https://docs.python.org/3.7/howto/logging.html#basic-logging-tutorial
  • 16.6. logging — Logging facility for Python — Python 3.7.0 documentation
    • https://docs.python.org/3.7/library/logging.html#logging.debug
    • https://docs.python.org/3.7/library/logging.html#logging.info
    • https://docs.python.org/3.7/library/logging.html#logging.basicConfig
    • https://docs.python.org/3.7/library/logging.html?highlight=shutdown#logging.shutdown
    • logging.basicConfig( filename=output.replace('html', 'log'), filemode='w', 

      format='[%(asctime)s] \n%(message)s', 

      datefmt='%Y-%m-%d %H:%M:%S', 

      level=logging.DEBUG )

  • Logging Cookbook — Python 3.7.0 documentation
    • https://docs.python.org/3/howto/logging-cookbook.html
  • Good logging practice in Python – Fang's coding note
    • https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/

How to measure execution time of code ?

How to import module from parent directory ?

How to parse arguments for command-line options ?

 1 import argparse
 2 
 3 if __name__ == "__main__":
 4     try:
 5         parser = argparse.ArgumentParser(prog='test',
 6                                          description='Test class A')
 7 
 8         parser.add_argument('-c',
 9                             '--config',
10                             metavar='file',
11                             help='Path to file',
12                             required=True)
13 
14         args = parser.parse_args()
15 
16         print("args.config = {0}\n".format(args.config))
17 
18     except (AttributeError, TypeError, RuntimeError) as err:
19         logger.logError(err.message)
20 
21     except Exception as err:
22         logger.logException(err.message)
View Code

How to fix AttributeError: MyBokeh instance has no attribute 'plot_all' ?

  • Check the indentation for other class member functions prior to plot_all()

How to fix TypeError: slice indices must be integers or None or have an __index__ method ?

  • b = ['a', 'aa', 'aaa', 'b', 'c']
  • d = [c for c in b if c.startswith( 'a', 'b' )]
  • It's due to lack of parenthese. Change to 
    • d = [c for c in b if c.startswith( ('a', 'b') )]

How to fix sqlite3.OperationalError: database is locked ?

  • SQLite is lightweight database and need to use, e.g. PostgrsSQL, for large number of connections. If the cache db file is in locked even if with one job, use the below cmds to recover it.
  • sqlite3 — DB-API 2.0 interface for SQLite databases — Python 3.7.4 documentation
    • https://docs.python.org/3.7/library/sqlite3.html
    • SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
  • SQLite Frequently Asked Questions
  • Python SQLite: database is locked - Stack Overflow
相关文章
相关标签/搜索