学习笔记之Python

Source Code

  • https://github.com/haoran119/learning-notes/tree/master/src/python

Welcome to Python.org

  • https://www.python.org/

3.6.3rc1 Documentation

  • https://docs.python.org/3/

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

  • https://www.python.org/dev/peps/pep-0008/

Python 入门指南 — Python tutorial 3.6.0 documentation

  • http://www.pythondoc.com/pythontutorial3/index.html

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

  • https://chuanke.baidu.com/course/_python_____.html

Download PyCharm: Python IDE for Professional Developers by JetBrains

  • https://www.jetbrains.com/pycharm/download/#section=mac

Python_百度百科

  • http://baike.baidu.com/view/21087.htm?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 3

  • https://www.cnblogs.com/pegasus923/p/10825575.html

Python Example

  • https://www.programcreek.com/python/

一文总结学习 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编程

  • https://mp.weixin.qq.com/s/r5ErQ7wh5wgN8sUYGiKJtg

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

  • https://www.cnblogs.com/pegasus923/p/10387079.html

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

  • https://mp.weixin.qq.com/s/RVbPKNmXg6EpsvXUDRoFNg
  • https://segmentfault.com/a/1190000012129654

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

  • https://mp.weixin.qq.com/s/jZ2ChI7xLCrehgFJP77xww
  • https://learnku.com/python/t/22976/python-tutorials-from-zero-to-master-suitable-for-experienced-developers
  • https://medium.freecodecamp.org/learning-python-from-zero-to-hero-120ea540b567

盘一盘 Python 系列 1 & 2 - 入门篇

  • https://mp.weixin.qq.com/s?__biz=MzIzMjY0MjE1MA==&mid=2247486473&idx=1&sn=e9228958bb5c425b8981261f14bd2f8c&chksm=e8908f00dfe70616fb3b87db7fcd054738322acbbacb1a08dbd81d36ab2c41cc56b7cc146394&scene=21#wechat_redirect
  • https://mp.weixin.qq.com/s?__biz=MzIzMjY0MjE1MA==&mid=2247486498&idx=1&sn=b5409de0fe394c49359eac9b67fb9ce4&chksm=e8908f2bdfe7063d2bb71587d621ff46f541f556e8a1abe828509bf3fef9144afd74580b47f8&scene=21#wechat_redirect

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

  • https://mp.weixin.qq.com/s/ovB8rsRvcjF-M5z2d5je8A
  • https://segmentfault.com/a/1190000015475309

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

  • https://mp.weixin.qq.com/s/bxhEr3HhxazS9gYhnrlBNA
  • https://www.linuxzen.com/python-you-ya-de-cao-zuo-zi-dian.html

ADVANCE

学习笔记之Python调试 - pdb - 浩然119 - 博客园

  • https://www.cnblogs.com/pegasus923/p/10437091.html

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

  • https://mp.weixin.qq.com/s/afhvyDGjt8U2XzHCZHOJJA

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生成器

  • https://mp.weixin.qq.com/s/2HAPquA-VZNNRHYRN8E2bg

为什么Python不用设计模式? - 码农翻身

  • https://mp.weixin.qq.com/s/HMZ0UJCGOS4GihjX_A5iNw

动态类型一时爽,代码重构火葬场? - Python爱好者社区

  • https://mp.weixin.qq.com/s/xjYK2f_ejVhshhn69uo7Cg

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

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

  • https://mp.weixin.qq.com/s/jaoMUy5okkMZ9QOYK-og1Q

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

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

理解python多线程和多进程

  • https://mp.weixin.qq.com/s/pjoSXrpjvxvOHDmWAhYfFA

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

  • https://mp.weixin.qq.com/s/w0dZrtv8ogdtxO8FT2LrEg

Python 正则表达式 re 模块简明笔记

  • https://mp.weixin.qq.com/s/8M_xiHMNB1a93ZunpxMsLg

Python Logging 模块完全解读

  • https://mp.weixin.qq.com/s/iZEjyEoxVUQ5cner2VY1kg

BEST PRACTICE

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

  • https://mp.weixin.qq.com/s/Vh2pwcI_PjtoagaVmz2dHw

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

  • https://mp.weixin.qq.com/s/V8x6clZRK6k9T2rXwj2aDQ

为什么Python这么慢? - Python编程

  • https://mp.weixin.qq.com/s/Wa-rMPIhGyb9JZt2g1YLHw
  • https://hackernoon.com/why-is-python-so-slow-e5074b6fe55b

入门 | 三行Python代码,让数据预处理速度提高2到6倍 - 机器之心

  • https://mp.weixin.qq.com/s/DgKuNIa_m-CsXWgHIz_3rQ
  • https://towardsdatascience.com/heres-how-you-can-get-a-2-6x-speed-up-on-your-data-pre-processing-with-python-847887e63be5

一行代码让 Python 的运行速度提高100倍 - 程序员大咖

  • https://mp.weixin.qq.com/s/5z-qAXreMolWhEdsjIpSfg
  • https://mp.weixin.qq.com/s/Vm0BKSljCzMMgRmIBbpxdQ

Python技巧 | 一行代码减少一半内存占用 - 机器学习算法与Python学习

  • https://mp.weixin.qq.com/s/0nTQ_oL2WWn8gytjqvn7SA

一文洞悉Python必备50种算法

  • https://mp.weixin.qq.com/s/n5Q8TrIZOTLXnvWSbkH8bA

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

  • https://mp.weixin.qq.com/s/1PyeBLIJNzswO3zd-mHiTQ
  • https://towardsdatascience.com/the-easy-way-to-work-with-csv-json-and-xml-in-python-5056f9325ca9

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

  • https://mp.weixin.qq.com/s/uzeBsCkCWCYmLdnZPQ-HBA

介绍几款 Python 类型检查工具 - Python中文社区

  • https://mp.weixin.qq.com/s/IvYJkpAmWJ-3ZEHtZzRiCQ

这些Python代码技巧,你肯定还不知道 - Python编程

  • https://mp.weixin.qq.com/s/UWd4hpeZztHmpHmmlftvlQ
  • https://medium.freecodecamp.org/an-a-z-of-useful-python-tricks-b467524ee747

wtfPython—Python中一些奇妙的代码 - Python编程

  • https://mp.weixin.qq.com/s/B--tL_s8-eWF-x9ilCbvdQ
  • http://yaoyaoblog.xyz/2017/09/04/wtfPython%E2%80%94Python%E4%B8%AD%E4%B8%80%E4%BA%9B%E5%A5%87%E5%A6%99%E7%9A%84%E4%BB%A3%E7%A0%81/

15个Pythonic的代码示例 - Python编程

  • https://mp.weixin.qq.com/s/vZcJ__SCcdLk2JopMx_yqA

写 Python 时的 5 个坏习惯,你有几条? - 机器学习算法与Python学习

  • https://mp.weixin.qq.com/s/TFx5yHAW4YdLdRrf_wusLA

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

  • https://mp.weixin.qq.com/s/rE5OEFwwFxJNb_Omwmqvzw
  • http://lovesoo.org/pythonic-python-programming.html

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

  • https://mp.weixin.qq.com/s/SU6TXpU3iiL8TZQO6dk02A
  • https://zhuanlan.zhihu.com/p/32817459

7个案例15分钟让你了解Python套路!- Python编程

  • https://mp.weixin.qq.com/s/8GQ8gP4S4yA7FmlLhbuiBA
  • https://www.jianshu.com/p/36ae91c38279

Python带我飞:50个有趣而又鲜为人知的Python特性 - Python编程

  • https://mp.weixin.qq.com/s/ULy82R1DYdbx0MH4xD22IA
  • https://github.com/leisurelicht/wtfpython-cn

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

  • https://mp.weixin.qq.com/s/sAS_NE8sIpw9ROOWSd60zw
  • https://blog.sicara.com/perfect-python-command-line-interfaces-7d5d4efad6a2

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

  • https://mp.weixin.qq.com/s/_-vCTkryiP2gq_IdX6pL8w
  • https://towardsdatascience.com/five-python-tricks-you-need-to-learn-today-9dbe03c790ab

Python中实用却不常见的小技巧 - Python爱好者社区

  • https://mp.weixin.qq.com/s/gEFe1AFq0oz8XlpjuFIqHg
  • https://hackernoon.com/python-tricks-101-2836251922e0
  • https://github.com/brennerm/PyTricks

Python 开发中有哪些高级技巧? - Python爱好者社区

  • https://mp.weixin.qq.com/s/6ierUk69wmooZcLKL3-XZw

18 个 Python 高效编程技巧 - Python二三事与机器学习算法

  • https://mp.weixin.qq.com/s/2Bxc5u0X_NQtLuXbVvPfzQ

Python的这些实用功能你都会了吗? - 机器学习算法与Python学习

  • https://mp.weixin.qq.com/s/6pE-3A7x4skXSZXCU-qhnA

Python 10大谬论 - 机器学习算法与Python学习

  • https://mp.weixin.qq.com/s/4UdLgFsZkt_Q_mdGOGHe4w

10 个不为人知的Python冷知识

  • https://mp.weixin.qq.com/s/NysJHFlw57Br_k1cpYTmMA

Python的高级特征你知多少

  • https://mp.weixin.qq.com/s/VBiQ2X7Y93h51GkIosC_Vw

26个Python实用技巧

  • https://mp.weixin.qq.com/s/ttuB63_N5SQdOhIwLFGYgg

18式优雅你的Python

  • https://mp.weixin.qq.com/s/iiG3Jarc_bIzcvz1-lmmhg

《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

如何多行字符串拼接?

 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

Conditional Expressions

  • 6. Expressions — Python 3.7.0 documentation
    • https://docs.python.org/3/reference/expressions.html?highlight=conditional%20expressions#conditional-expressions
  • 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

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 ?

  • 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 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 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

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 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 debug python program ?

  • 28.3. pdb — The Python Debugger — Python 3.7.0 documentation
    • https://docs.python.org/3/library/pdb.html
  • debugging - Can you step through python code to help debug issues? - Stack Overflow
    • https://stackoverflow.com/questions/4929251/can-you-step-through-python-code-to-help-debug-issues

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 import module from parent directory ?

  • import sys
  • sys.path.append('..')
  • from A import B
  • python - Importing modules from parent folder - Stack Overflow
    • https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder

How to parse arguments for command-line options ?

  • 15.4. argparse — Parser for command-line options, arguments and sub-commands — Python 2.7.16 documentation
    • https://docs.python.org/2.7/library/argparse.html?highlight=arg%20parse#the-add-argument-method
  • python - What's the best way to parse command line arguments? - Stack Overflow
    • https://stackoverflow.com/questions/20063/whats-the-best-way-to-parse-command-line-arguments
  • python - Why use argparse rather than optparse? - Stack Overflow
    • https://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
 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') )]

转载于:https://www.cnblogs.com/pegasus923/p/4006785.html

你可能感兴趣的:(学习笔记之Python)