这是一个非常全面的 Python 备忘单,适合任何感兴趣的人。它绝对是可用的最详细的之一。点击标题
- 1. 集合Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator.
- 2. 类型: Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime.
- 3. 语法: Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception.
- 4. 系统: Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands.
- 5. 数据: JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque.
- 6. 高级: Threading, Operator, Introspection, Metaprograming, Eval, Coroutines.
- 7. 库包: Progress_Bar, Plot, Tables, Curses, Logging, Scraping, Web, Profile.
- 8. Multimedia: NumPy, Image, Animation, Audio, Pygame, Pandas, Plotly, PySimpleGUI.
列表
<list> = <list>[<slice>] # Or: <list>[from_inclusive : to_exclusive : ±step] |
sum_of_elements = sum(<collection>) |
有关 Sorted()、min() 和 max() 的详细信息,请参阅sortable。
模块运算符提供了函数 itemgetter() 和 mul(),它们提供与上面的[url=https://github.com/gto76/python-cheatsheetlambda]lambda[/url]表达式相同的功能。
<list>.insert(<int>, <el>) # 插入索引处的项目,并将其余项目向右移动。 |
字典
<view> = <dict>.keys() # 反映变化的按键总数。 |
Set
<set> = set() # `{}` returns a dictionary. |
Tuple
Tuple 是不可变且可散列的列表。
<tuple> = () # Empty tuple. |
Type类型
- 一切都是对象。
- 每个对象都有一个类型。
- 类型和类是同义词。
<type> = type(<el>) # Or: <el>.__class__ |
有些类型没有内置名称,因此必须导入:
from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType
String字符
不可变字符集
<str> = <str>.strip() # 删除两端的所有空白字符。 |
正则
正则表达式匹配函数
import re |
- 参数 "new "可以是一个接受 Match 对象并返回字符串的函数。
- 参数 "flags=re.IGNORECASE "可用于所有函数。
- 参数'flags=re.MULTILINE'会使'^'和'$'匹配每一行的起始/结束位置。
- 参数'flags=re.DOTALL'使'.'也接受'\n'。
- 使用 r'\1' 或 '\1' 进行反向引用('\1' 返回八进制代码为 1 的字符)。
- 在'*'和'+'后面添加'?
格式:
<str> = f'{<el_1>}, {<el_2>}' 大括号也可以包含表达式。 |
>>> Person = collections.namedtuple('Person', 'name height') |
字符Strings
{'abcde':10} # 'abcde ' |
数字Numbers
{123456:10} # ' 123456' |
Floats浮点
{1.23456:10.3} # ' 1.23' |
整数
{90:c} # 'Z' |
<int> = int(<float/str/bool>) # Or: math.floor(<float>) |
- int(<str>)'和'float(<str>)'会对畸形字符串引发 ValueError。
- 十进制数是精确存储的,不像大多数浮点数那样 "1.1 + 2.2 != 3.3"。
- 浮点数可以用math.isclose(<float>,<float>)"。
- 十进制运算的精度可以用'decimal.getcontext().prec = <int>'。
组合
import itertools as it |
日期时间
提供 "日期"、"时间"、"datetime "和 "timedelta "类。所有类都不可变且可散列。
# pip3 install python-dateutil |
<D> = date(year, month, day) # 只接受公元 1 至 9999 年的有效日期。 |
- Aware <a> 时间和日期时间对象有定义的时区,而 naive <n> 没有。如果对象是幼稚的,则假定它处于系统时区!
- fold=1 "表示在时间向后跳转一小时的情况下进行第二次跳转。
- Timedelta 会将参数标准化为±日、秒(< 86 400)和微秒(< 1M)。
- 使用"<D/DT>.weekday() "以 int 表示星期几,星期一为 0。
<D/DTn> = D/DT.today() # 当前本地日期或天真 DT。也是 DT.now()。 |
- 由 gettz()、tzlocal() 和 naive 对象的隐式本地时区返回的时区,其偏移量会因 DST 和时区基准偏移量的历史变化而随时间变化。
- 在 Python 3.9 及更高版本中,可以使用标准库的 zoneinfo.ZoneInfo() 代替 gettz()。在 Windows 上,它需要 "tzdata "软件包。如果省略 arg.,则不会返回本地 tz。
Class类
class <name>: |
- repr() 的返回值应明确无误,str() 的返回值也应可读。
- 如果只定义了 repr(),它也将用于 str()。
- 使用"@staticmethod "装饰的方法不会将 "self "或 "cls "作为第一个参数。
更多完整列表备忘录点击标题