综合 Python 备忘单
March 17, 2024 2024 年 3 月 17 日Jure Šorn 尤雷·索恩
Comprehensive Python Cheatsheet
Download text file, Buy PDF, Fork me on GitHub, Check out FAQ or Switch to light theme.
#Contents 目录
ToC = {
'1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
'2. Types': [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],
'3. Syntax': [Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception],
'4. System': [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
'5. Data': [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
'6. Advanced': [Threading, Operator, Match_Stmt, Logging, Introspection, Coroutines],
'7. Libraries': [Progress_Bar, Plots, Tables, Curses, GUIs, Scraping, Web, Profiling],
'8. Multimedia': [NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly]
}
#Main 主函数
if __name__ == '__main__': # Runs main() if file wasn't imported.
main()
#List 列表
<list> = <list>[<slice>] # Or: <list>[from_inclusive : to_exclusive : ±step]
<list>.append(<el>) # Or: <list> += [<el>]
<list>.extend(<collection>) # Or: <list> += <collection>
<list>.sort() # Sorts in ascending order.
<list>.reverse() # Reverses the list in-place.
<list> = sorted(<collection>) # Returns a new sorted list.
<iter> = reversed(<list>) # Returns reversed iterator.
sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
sorted_by_second = sorted(<collection>, key=lambda el: el[1])
sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars = list(<str>)
- For details about sorted(), min() and max() see sortable. 有关sorted()、min() 和max() 的详细信息,请参阅 sortable。
- Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above. 模块运算符提供了函数 itemgetter() 和 mul(),它们提供与上面的 lambda 表达式相同的功能。
<list>.insert(<int>, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([<int>]) # Removes and returns item at index or from the end.
<int> = <list>.count(<el>) # Returns number of occurrences. Also works on strings.
<int> = <list>.index(<el>) # Returns index of the first occurrence or raises ValueError.
<list>.remove(<el>) # Removes first occurrence of the item or raises ValueError.
<list>.clear() # Removes all items. Also works on dictionary and set.
# Dictionary 字典
<view> = <dict>.keys() # Coll. of keys that reflects changes.
<view> = <dict>.values() # Coll. of values that reflects changes.
<view> = <dict>.items() # Coll. of key-value tuples that reflects chgs.
value = <dict>.get(key, default=None) # Returns default if key is missing.
value = <dict>.setdefault(key, default=None) # Returns and writes default if key is missing.
<dict> = collections.defaultdict(<type>) # Returns a dict with default value `<type>()`.
<dict> = collections.defaultdict(lambda: 1) # Returns a dict with default value 1.
<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
<dict> = dict(zip(keys, values)) # Creates a dict from two collections.
<dict> = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
<dict>.update(<dict>) # Adds items. Replaces ones with matching keys.
value = <dict>.pop(key) # Removes item or raises KeyError if missing.
{k for k, v in <dict>.items() if v == value} # Returns set of keys that point to the value.
{k: v for k, v in <dict>.items() if k in keys} # Filters the dictionary by keys.
Counter 计算器
>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
#Set 集
<set> = set() # `{}` returns a dictionary.
<set>.add(<el>) # Or: <set> |= {<el>}
<set>.update(<collection> [, ...]) # Or: <set> |= <set>
<set> = <set>.union(<coll.>) # Or: <set> | <set>
<set> = <set>.intersection(<coll.>) # Or: <set> & <set>
<set> = <set>.difference(<coll.>) # Or: <set> - <set>
<set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
<bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
<bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
<el> = <set>.pop() # Raises KeyError if empty.
<set>.remove(<el>) # Raises KeyError if missing.
<set>.discard(<el>) # Doesn't raise an error.
Frozen Set 冻集
- Is immutable and hashable. 是不可变且可散列的。
- That means it can be used as a key in a dictionary or as an element in a set. 这意味着它可以用作字典中的键或集合中的元素。
<frozenset> = frozenset(<collection>)
#Tuple 元组
Tuple is an immutable and hashable list. 元组是一个不可变且可哈希的列表。
<tuple> = () # Empty tuple.
<tuple> = (<el>,) # Or: <el>,
<tuple> = (<el_1>, <el_2> [, ...]) # Or: <el_1>, <el_2> [, ...]
Named Tuple 命名元组
Tuple's subclass with named elements. Tuple 的子类具有命名元素。
>>> from collections import namedtuple
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(1, y=2)
Point(x=1, y=2)
>>> p[0]
1
>>> p.x
1
>>> getattr(p, 'y')
2
#Range 范围
Immutable and hashable sequence of integers. 不可变且可散列的整数序列。
<range> = range(stop) # range(to_exclusive)
<range> = range(start, stop) # range(from_inclusive, to_exclusive)
<range> = range(start, stop, ±step) # range(from_inclusive, to_exclusive, ±step_size)
>>> [i for i in range(3)]
[0, 1, 2]
#Enumerate 枚举
for i, el in enumerate(<collection> [, i_start]):
...
#Iterator 迭代器
<iter> = iter(<collection>) # `iter(<iter>)` returns unmodified iterator.
<iter> = iter(<function>, to_exclusive) # A sequence of return values until 'to_exclusive'.
<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
<list> = list(<iter>) # Returns a list of iterator's remaining elements.
Itertools 迭代工具
import itertools as it
<iter> = it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
<iter> = it.repeat(<el> [, times]) # Returns element endlessly or 'times' times.
<iter> = it.cycle(<collection>) # Repeats the sequence endlessly.
<iter> = it.chain(<coll>, <coll> [, ...]) # Empties collections in order (figuratively).
<iter> = it.chain.from_iterable(<coll>) # Empties collections inside a collection in order.
<iter> = it.islice(<coll>, to_exclusive) # Only returns first 'to_exclusive' elements.
<iter> = it.islice(<coll>, from_inc, …) # `to_exclusive, +step_size`. Indices can be None.
#Generator 生成器
- Any function that contains a yield statement returns a generator. 任何包含yield 语句的函数都会返回一个生成器。
- Generators and iterators are interchangeable. 生成器和迭代器是可以互换的。
def count(start, step):
while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
#Type 类型
- Everything is an object. 一切都是对象。
- Every object has a type. 每个对象都有一个类型。
- Type and class are synonymous. type和class是同义词。
<type> = type(<el>) # Or: <el>.__class__
<bool> = isinstance(<el>, <type>) # Or: issubclass(type(<el>), <type>)
>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)
Some types do not have built-in names, so they must be imported: 有些类型(types)没有内置名称,因此必须导入:
from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType
Abstract Base Classes 抽象基类
Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. 每个抽象基类指定一组虚拟子类。然后,这些类被 isinstance() 和 issubclass() 识别为 ABC 的子类,尽管它们实际上不是。 ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len(). ABC 还可以手动决定特定类是否是其虚拟子类,通常基于该类实现了哪些方法。例如,Iterable ABC 会寻找 iter() 方法,而 Collection ABC 会寻找 iter()、contains() 和 len() 方法。
>>> from collections.abc import Iterable, Collection, Sequence
>>> isinstance([1, 2, 3], Iterable)
True
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┃ │ Iterable │ Collection │ Sequence ┃
┠──────────────────┼────────────┼────────────┼────────────┨
┃ list, range, str │ ✓ │ ✓ │ ✓ ┃
┃ dict, set │ ✓ │ ✓ │ ┃
┃ iter │ ✓ │ │ ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
>>> from numbers import Number, Complex, Real, Rational, Integral
>>> isinstance(123, Number)
True
┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┃ │ Number │ Complex │ Real │ Rational │ Integral ┃
┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ fractions.Fraction │ ✓ │ ✓ │ ✓ │ ✓ │ ┃
┃ float │ ✓ │ ✓ │ ✓ │ │ ┃
┃ complex │ ✓ │ ✓ │ │ │ ┃
┃ decimal.Decimal │ ✓ │ │ │ │ ┃
┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
#String 字符串
Immutable sequence of characters. 不可变的字符序列。
<str> = <str>.strip() # 去除两端的所有空白字符。Strips all whitespace characters from both ends.
<str> = <str>.strip('<chars>') # 删除传递的字符。包括 lstrip/rstrip()。Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split() # 根据一个或多个空白字符进行拆分。Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1) # 在 'sep' str 上最多分割 'maxsplit' 次。Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False) # 在 [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] 和 \r\n 上。On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str> = <str>.join(<coll_of_strings>) # 使用字符串作为分隔符连接元素。Joins elements using string as a separator.
<bool> = <sub_str> in <str> # 检查字符串是否包含子字符串。Checks if string contains the substring.
<bool> = <str>.startswith(<sub_str>) # 为多个选项传递字符串元组。Pass tuple of strings for multiple options.
<int> = <str>.find(<sub_str>) # 返回第一个匹配的开始索引或-1。Returns start index of the first match or -1.
<int> = <str>.index(<sub_str>) # 相同,但如果缺失则引发 ValueError。Same, but raises ValueError if missing.
<str> = <str>.lower() # 更改大小写。还有 大写/大写/标题()。Changes the case. Also upper/capitalize/title().
<str> = <str>.replace(old, new [, count]) # 最多将“旧”替换为“新”次。Replaces 'old' with 'new' at most 'count' times.
<str> = <str>.translate(<table>) # 使用 `str.maketrans(<dict>)` 生成表。Use `str.maketrans(<dict>)` to generate table.
<str> = chr(<int>) # 将 int 转换为 Unicode 字符。Converts int to Unicode character.
<int> = ord(<str>) # 将 Unicode 字符转换为 int。Converts Unicode character to int.
- Use
'unicodedata.normalize("NFC", <str>)'on strings like'Motörhead'before comparing them to other strings, because'ö'can be stored as one or two characters. 在将诸如'Motörhead'之类的字符串与其他字符串进行比较之前,请使用'unicodedata.normalize("NFC", <str>)',因为'ö'可以存储为一个或两个字符。 'NFC'converts such characters to a single character, while'NFD'converts them to two.'NFC'将这些字符转换为单个字符,而'NFD'将它们转换为两个字符。
Property Methods 属性方法
<bool> = <str>.isdecimal() # Checks for [0-9]. Also [०-९] and [٠-٩].
<bool> = <str>.isdigit() # Checks for [²³¹…] and isdecimal().
<bool> = <str>.isnumeric() # Checks for [¼½¾], [零〇一…] and isdigit().
<bool> = <str>.isalnum() # Checks for [a-zA-Z…] and isnumeric().
<bool> = <str>.isprintable() # Checks for [ !#$%…] and isalnum().
<bool> = <str>.isspace() # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…].
#Regex 正则表达式
Functions for regular expression matching. 正则表达式匹配的函数。
import re
<str> = re.sub(r'<regex>', new, text, count=0) # 将所有出现的情况替换为“新”。Substitutes all occurrences with 'new'.
<list> = re.findall(r'<regex>', text) # 以字符串形式返回所有出现的情况。Returns all occurrences as strings.
<list> = re.split(r'<regex>', text, maxsplit=0) # 在正则表达式周围添加括号以保持匹配。Add brackets around regex to keep matches.
<Match> = re.search(r'<regex>', text) # 模式第一次出现或无。First occurrence of the pattern or None.
<Match> = re.match(r'<regex>', text) # 仅在文本开头搜索。Searches only at the beginning of the text.
<iter> = re.finditer(r'<regex>', text) # 将所有出现的情况作为 Match 对象返回。Returns all occurrences as Match objects.
- Raw string literals do not interpret escape sequences, thus enabling us to use regex-specific escape sequences that cause SyntaxWarning in normal string literals (since 3.12). 原始字符串文字不解释转义序列,因此使我们能够使用特定于正则表达式的转义序列,这些转义序列会在普通字符串文字中导致 SyntaxWarning(自 3.12 起)。
- Argument 'new' of re.sub() can be a function that accepts a Match object and returns a str. re.sub() 的参数“new”可以是接受 Match 对象并返回 str 的函数。
- Argument
'flags=re.IGNORECASE'can be used with all functions. 参数'flags=re.IGNORECASE'可与所有函数一起使用。 - Argument
'flags=re.MULTILINE'makes'^'and'$'match the start/end of each line. 参数'flags=re.MULTILINE'使'^'和'$'匹配每行的开头/结尾。 - Argument
'flags=re.DOTALL'makes'.'also accept the'\n'. 参数'flags=re.DOTALL'使'.'也接受'\n'。 're.compile(<regex>)'returns a Pattern object with methods sub(), findall(), …'re.compile(<regex>)'返回一个带有方法 sub()、findall() 等方法的 Pattern 对象
Match Object 匹配对象
<str> = <Match>.group() # 返回整个匹配。相当于group(0)。Returns the whole match. Also group(0).
<str> = <Match>.group(1) # 返回第一个brackets(匹配相等的)的部分。Returns part inside the first brackets.
<tuple> = <Match>.groups() # 返回所有brackets(匹配相等的)部分。Returns all bracketed parts.
<int> = <Match>.start() # 返回匹配的开始索引。Returns start index of the match.
<int> = <Match>.end() # 返回匹配的唯一结束索引。Returns exclusive end index of the match.
Special Sequences 特殊序列
'\d' == '[0-9]' # Also [०-९…]. Matches a decimal character.
'\w' == '[a-zA-Z0-9_]' # Also [ª²³…]. Matches an alphanumeric or _.
'\s' == '[ \t\n\r\f\v]' # Also [\x1c-\x1f…]. Matches a whitespace.
- By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless
'flags=re.ASCII'argument is used. 默认情况下,除非使用'flags=re.ASCII'参数,否则所有字母表中的十进制字符、字母数字和空格都会匹配。 - It restricts special sequence matches to
'[\x00-\x7f]'(the first 128 characters) and also prevents'\s'from accepting'[\x1c-\x1f]'(the so-called separator characters). 它将特殊序列匹配限制为'[\x00-\x7f]'(前 128 个字符),并阻止'\s'接受'[\x1c-\x1f]'(所谓的分隔符)。 - Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag). 使用大写字母进行否定(与 ASCII 标志结合使用时将匹配所有非 ASCII 字符)。
#Format 格式
<str> = f'{<el_1>}, {<el_2>}' # f-string: 大括号内还可以包含表达式。 Curly brackets can also contain expressions.
<str> = '{}, {}'.format(<el_1>, <el_2>) # 或者Or: '{0}, {a}'.format(<el_1>, a=<el_2>)
<str> = '%s, %s' % (<el_1>, <el_2>) # 冗余、沿用的C语言风格格式化。 Redundant and inferior C-style formatting.
Example 例子
>>> Person = collections.namedtuple('Person', 'name height')
>>> person = Person('Jean-Luc', 187)
>>> f'{person.name} is {person.height / 100} meters tall.'
'Jean-Luc is 1.87 meters tall.'
General Options 常规选项(对齐和填充的方式)
{<el>:<10} # '<el> '
{<el>:^10} # ' <el> '
{<el>:>10} # ' <el>'
{<el>:.<10} # '<el>......'
{<el>:0} # '<el>'
- Objects are rendered using
'format(<el>, <options>)'. 对象使用'format(<el>, <options>)'渲染。 - Options can be generated dynamically:
f'{<el>:{<str/int>}[…]}'. 选项可以动态生成:f'{<el>:{<str/int>}[…]}'。 - Adding
'='to the expression prepends it to the output:f'{1+1=}'returns'1+1=2'. 将'='添加到表达式会将其添加到输出前面:f'{1+1=}'返回'1+1=2'。 - Adding
'!r'to the expression converts object to string by calling its repr() method. 将'!r'添加到表达式中可通过调用其 repr() 方法将对象转换为字符串。
Strings 字符串
{'abcde':10} # 'abcde '
{'abcde':10.3} # 'abc '
{'abcde':.3} # 'abc'
{'abcde'!r:10} # "'abcde' "
Numbers 数字
{123456:10} # ' 123456'
{123456:10,} # ' 123,456'
{123456:10_} # ' 123_456'
{123456:+10} # ' +123456'
{123456:=+10} # '+ 123456'
{123456: } # ' 123456'
{-123456: } # '-123456'
Floats 花车
{1.23456:10.3} # ' 1.23'
{1.23456:10.3f} # ' 1.235'
{1.23456:10.3e} # ' 1.235e+00'
{1.23456:10.3%} # ' 123.456%'
Comparison of presentation types: 演示类型比较:
┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
┃ │ {<float>} │ {<float>:f} │ {<float>:e} │ {<float>:%} ┃
┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
┃ 0.000056789 │ '5.6789e-05' │ '0.000057' │ '5.678900e-05' │ '0.005679%' ┃
┃ 0.00056789 │ '0.00056789' │ '0.000568' │ '5.678900e-04' │ '0.056789%' ┃
┃ 0.0056789 │ '0.0056789' │ '0.005679' │ '5.678900e-03' │ '0.567890%' ┃
┃ 0.056789 │ '0.056789' │ '0.056789' │ '5.678900e-02' │ '5.678900%' ┃
┃ 0.56789 │ '0.56789' │ '0.567890' │ '5.678900e-01' │ '56.789000%' ┃
┃ 5.6789 │ '5.6789' │ '5.678900' │ '5.678900e+00' │ '567.890000%' ┃
┃ 56.789 │ '56.789' │ '56.789000' │ '5.678900e+01' │ '5678.900000%' ┃
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
┃ │ {<float>:.2} │ {<float>:.2f} │ {<float>:.2e} │ {<float>:.2%} ┃
┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
┃ 0.000056789 │ '5.7e-05' │ '0.00' │ '5.68e-05' │ '0.01%' ┃
┃ 0.00056789 │ '0.00057' │ '0.00' │ '5.68e-04' │ '0.06%' ┃
┃ 0.0056789 │ '0.0057' │ '0.01' │ '5.68e-03' │ '0.57%' ┃
┃ 0.056789 │ '0.057' │ '0.06' │ '5.68e-02' │ '5.68%' ┃
┃ 0.56789 │ '0.57' │ '0.57' │ '5.68e-01' │ '56.79%' ┃
┃ 5.6789 │ '5.7' │ '5.68' │ '5.68e+00' │ '567.89%' ┃
┃ 56.789 │ '5.7e+01' │ '56.79' │ '5.68e+01' │ '5678.90%' ┃
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
'{<float>:g}'is'{<float>:.6}'with stripped zeros, exponent starting at'1e+06'.'{<float>:g}'是'{<float>:.6}',去掉了零,指数从'1e+06'开始。- When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes
'{6.5:.0f}'a'6'and'{7.5:.0f}'an'8'. 当向上舍入和向下舍入都可能时,选择返回结果为偶数的结果。这使得'{6.5:.0f}'成为'6','{7.5:.0f}'成为'8'。 - This rule only effects numbers that can be represented exactly by a float (
.5,.25, …). 此规则仅影响可由浮点精确表示的数字(.5、.25等)。
Ints 整数
{90:c} # 'Z'
{90:b} # '1011010'
{90:X} # '5A'
#Numbers 数字
<int> = int(<float/str/bool>) # Or: math.floor(<float>)
<float> = float(<int/str/bool>) # Or: <int/float>e±<int>
<complex> = complex(real=0, imag=0) # Or: <int/float> ± <int/float>j
<Fraction> = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1)
<Decimal> = decimal.Decimal(<str/int>) # Or: Decimal((sign, digits, exponent))
'int(<str>)'and'float(<str>)'raise ValueError on malformed strings.'int(<str>)'和'float(<str>)'在格式错误的字符串上引发 ValueError。- Decimal numbers are stored exactly, unlike most floats where
'1.1 + 2.2 != 3.3'. 十进制数字被精确存储,这与大多数浮点数'1.1 + 2.2 != 3.3'不同。 - Floats can be compared with:
'math.isclose(<float>, <float>)'. 浮点数可以与:'math.isclose(<float>, <float>)'进行比较。 - Precision of decimal operations is set with:
'decimal.getcontext().prec = <int>'. 小数运算的精度设置为:'decimal.getcontext().prec = <int>'。
Basic Functions 基础函数
<num> = pow(<num>, <num>) # 幂函数 Or: <num> ** <num>
<num> = abs(<num>) # 绝对值 <float> = abs(<complex>)
<num> = round(<num> [, ±ndigits]) # 取整数 `round(126, -1) == 130`
Math 数学
from math import e, pi, inf, nan, isinf, isnan # 常数 `<el> == nan` is always False.
from math import sin, cos, tan, asin, acos, atan # 三角函数 Also: degrees, radians.
from math import log, log10, log2 # 指数函数 Log can accept base as second arg.
Statistics 统计数据
from statistics import mean, median, variance # mean(data) 用于求给定序列或者迭代器的算术平均数; median(data) 计算数据的中位数;variance(data, xbar=None) 用于计算数据的样本方差
from statistics import stdev, quantiles, groupby # stdev(data, xbar=None) 用于计算数据的样本标准差。 quantiles() 用于计算给定数据集的分位数。groupby())用于分组统计.
Random 随机的
from random import random, randint, choice # 还有: shuffle(随机打乱一个序列,例如列表或字符串。这个函数能够对序列进行原地修改,也就是说,它将直接影响原始序列,而不是返回一个新的序列), gauss(mu, sigma) 函数来生成一个高斯分布的随机数,其中 mu 是平均值,sigma 是标准差。, triangular(low, high, mode=None)(返回一个符合三角分布的随机浮点数), seed.
<float> = random() # [0, 1)之间的随机浮点数 A float inside [0, 1).
<int> = randint(from_inc, to_inc) # [from_inc, to_inc]之间的随机整数 An int inside [from_inc, to_inc].
<el> = choice(<sequence>) # 从队列中随机抽取一个 Keeps the sequence intact.
Bin, Hex 二进制,十六进制
<int> = ±0b<bin> # Or: ±0x<hex>
<int> = int('±<bin>', 2) # Or: int('±<hex>', 16)
<int> = int('±0b<bin>', 0) # Or: int('±0x<hex>', 0)
<str> = bin(<int>) # Returns '[-]0b<bin>'.
Bitwise Operators 按位运算符
<int> = <int> & <int> # 与And (0b1100 & 0b1010 == 0b1000).
<int> = <int> | <int> # 或Or (0b1100 | 0b1010 == 0b1110).
<int> = <int> ^ <int> # 亦或Xor (0b1100 ^ 0b1010 == 0b0110).
<int> = <int> << n_bits # 左移Left shift. Use >> for right右移.
<int> = ~<int> # 否Not. Also -<int> - 1.
#Combinatorics 组合
import itertools as it
>>> list(it.product([0, 1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
>>> list(it.product('abc', 'abc')) # a b c
[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x
('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x
('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x
>>> list(it.combinations('abc', 2)) # a b c
[('a', 'b'), ('a', 'c'), # a . x x
('b', 'c')] # b . . x
>>> list(it.combinations_with_replacement('abc', 2)) # a b c
[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x
('b', 'b'), ('b', 'c'), # b . x x
('c', 'c')] # c . . x
>>> list(it.permutations('abc', 2)) # a b c
[('a', 'b'), ('a', 'c'), # a . x x
('b', 'a'), ('b', 'c'), # b x . x
('c', 'a'), ('c', 'b')] # c x x .
#Datetime 日期时间
Provides 'date', 'time', 'datetime' and 'timedelta' classes. All are immutable and hashable. 提供“日期”、“时间”、“日期时间”和“时间增量”类。一切都是不可变和可哈希的。
# $ pip3 install python-dateutil
from datetime import date, time, datetime, timedelta, timezone
from dateutil.tz import tzlocal, gettz
<D> = date(year, month, day) # Only accepts valid dates from 1 to 9999 AD.
<T> = time(hour=0, minute=0, second=0) # Also: `microsecond=0, tzinfo=None, fold=0`.
<DT> = datetime(year, month, day, hour=0) # Also: `minute=0, second=0, microsecond=0, …`.
<TD> = timedelta(weeks=0, days=0, hours=0) # Also: `minutes=0, seconds=0, microseconds=0`.
- Aware
<a>time and datetime objects have defined timezone, while naive<n>don't. If object is naive, it is presumed to be in the system's timezone! 注意<a>时间和日期时间对象已定义时区,而naive的<n>则没有。如果对象是naive的,则假定它位于系统的时区中! 'fold=1'means the second pass in case of time jumping back for one hour.'fold=1'表示如果时间回跳到一小时需要消耗的秒数。- Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Timedelta 将参数标准化为 ± 天、秒 (< 86400) 和微秒 (< 1M)。
- Use
'<D/DT>.weekday()'to get the day of the week as an int, with Monday being 0. 使用'<D/DT>.weekday()'获取整数形式的星期几,其中星期一为 0。
Now 现在
<D/DTn> = D/DT.today() # 当前的本地日期/时间 Current local date or naive DT. Also DT.now().
<DTa> = DT.now(<tzinfo>) # 带时区的当前时间 Aware DT from current time in passed timezone.
- To extract time use
'<DTn>.time()','<DTa>.time()'or'<DTa>.timetz()'. 要提取时间,请使用'<DTn>.time()'、'<DTa>.time()'或'<DTa>.timetz()'。
Timezone 时区
<tzinfo> = timezone.utc # 伦敦没有夏令时 (DST)。 London without daylight saving time (DST).
<tzinfo> = timezone(<timedelta>) # 与 UTC 具有固定偏移量的时区。 Timezone with fixed offset from UTC.
<tzinfo> = tzlocal() # 具有动态偏移的局部 tz。还有 gettz()。 Local tz with dynamic offset. Also gettz().
<tzinfo> = gettz('<Continent>/<City>') # “Continent/City_Name”时区或无。 'Continent/City_Name' timezone or None.
<DTa> = <DT>.astimezone([<tzinfo>]) # 将 DT 转换为已传递或本地固定区域。 Converts DT to the passed or local fixed zone.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # 更改对象的时区而不进行转换。 Changes object's timezone without conversion.
- Timezones returned by gettz(), tzlocal(), and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the zone's base offset. gettz()、tzlocal() 返回的时区和朴素对象的隐式本地时区的偏移量会因 DST 和区域基本偏移量的历史变化而随时间变化。
- Standard library's zoneinfo.ZoneInfo() can be used instead of gettz() on Python 3.9 and later. It requires 'tzdata' package on Windows. It doesn't return local tz if arg. is omitted. 在 Python 3.9 及更高版本上,可以使用标准库的 zoneinfo.ZoneInfo() 代替 gettz()。它需要 Windows 上的“tzdata”包。如果 arg.它不返回本地 tz。被省略。
Encode 编码
<D/T/DT> = D/T/DT.fromisoformat(<str>) # 来自 ISO 字符串的对象。引发 ValueError。 Object from ISO string. Raises ValueError.
<DT> = DT.strptime(<str>, '<format>') # 根据格式,来自 str 的日期时间。 Datetime from str, according to format.
<D/DTn> = D/DT.fromordinal(<int>) # D/DT 自公历新年 1 日起计算。 D/DT from days since the Gregorian NYE 1.
<DTn> = DT.fromtimestamp(<float>) # 自纪元以来的几秒内的本地朴素 DT。 Local naive DT from seconds since the Epoch.
<DTa> = DT.fromtimestamp(<float>, <tz>) # 了解自纪元以来的秒数日期时间。 Aware datetime from seconds since the Epoch.
- ISO strings come in following forms:
'YYYY-MM-DD','HH:MM:SS.mmmuuu[±HH:MM]', or both separated by an arbitrary character. All parts following the hours are optional. ISO 字符串采用以下形式:'YYYY-MM-DD'、'HH:MM:SS.mmmuuu[±HH:MM]'或两者均由任意字符分隔。小时后的所有部分都是可选的。 - Python uses the Unix Epoch:
'1970-01-01 00:00 UTC','1970-01-01 01:00 CET', … Python 使用 Unix Epoch:'1970-01-01 00:00 UTC'、'1970-01-01 01:00 CET'、...
Decode 解码
<str> = <D/T/DT>.isoformat(sep='T') # 还有 `timespec='auto/小时/分钟/秒/...'`。 Also `timespec='auto/hours/minutes/seconds/…'`.
<str> = <D/T/DT>.strftime('<format>') # 对象的自定义字符串表示形式。 Custom string representation of the object.
<int> = <D/DT>.toordinal() # 自公历 NYE 1 起的天数,忽略时间和 tz。 Days since Gregorian NYE 1, ignoring time and tz.
<float> = <DTn>.timestamp() # 自 Epoch 以来的秒数,来自本地幼稚 DT。 Seconds since the Epoch, from local naive DT.
<float> = <DTa>.timestamp() # 自纪元以来的秒数(从已知日期时间算起)。 Seconds since the Epoch, from aware datetime.
Format 格式
>>> dt = datetime.strptime('2025-08-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
>>> dt.strftime("%dth of %B '%y (%a), %I:%M %p %Z")
"14th of August '25 (Thu), 11:39 PM UTC+02:00"
'%z'accepts'±HH[:]MM'and returns'±HHMM'or empty string if datetime is naive.'%z'接受'±HH[:]MM'并返回'±HHMM'或空字符串(如果日期时间很简单)。'%Z'accepts'UTC/GMT'and local timezone's code and returns timezone's name,'UTC[±HH:MM]'if timezone is nameless, or an empty string if datetime is naive.'%Z'接受'UTC/GMT'和本地时区的代码,并返回时区的名称,如果时区无名,则返回'UTC[±HH:MM]';如果日期时间很幼稚,则返回空字符串。
Arithmetics 算术
<bool> = <D/T/DTn> > <D/T/DTn> # 忽略时间跳跃(fold折叠属性)。还有==。 Ignores time jumps (fold attribute). Also ==.
<bool> = <DTa> > <DTa> # 如果它们共享 tz 对象,则忽略跳转。破了==。 Ignores jumps if they share tz object. Broken ==.
<TD> = <D/DTn> - <D/DTn> # 忽略跳跃。转换为 UTC 以获得实际增量。 Ignores jumps. Convert to UTC for actual delta.
<TD> = <DTa> - <DTa> # 如果它们共享 tzinfo 对象,则忽略跳转。 Ignores jumps if they share tzinfo object.
<D/DT> = <D/DT> ± <TD> # 返回的日期时间可能会落入缺失的小时。 Returned datetime can fall into missing hour.
<TD> = <TD> * <float> # 另外:<TD> = abs(<TD>) 且 <TD> = <TD> ±% <TD>。 Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>.
<float> = <TD> / <TD> # TD 有多少小时/周/年。还 //。 How many hours/weeks/years are in TD. Also //.
#Arguments 参数
Inside Function Call 内部函数调用
func(<positional_args>) # 固定位置参数 func(0, 0)
func(<keyword_args>) # 关键字参数 func(x=0, y=0)
func(<positional_args>, <keyword_args>) # 固定位置参数+关键字参数 func(0, y=0)
Inside Function Definition 内部函数定义
def func(<nondefault_args>): ... # def func(x, y): ...
def func(<default_args>): ... # def func(x=0, y=0): ...
def func(<nondefault_args>, <default_args>): ... # def func(x, y=0): ...
- Default values are evaluated when function is first encountered in the scope. 当函数在作用域中第一次遇到时,将评估默认值。
- Any mutation of a mutable default value will persist between invocations! 可变默认值的任何变化都将在调用之间持续存在!
#Splat Operator #Splat 操作【星号】
注:Python 中的“splat”运算符是一个术语,在函数调用、解包迭代和定义函数参数时经常用来指代星号*。它的正式名称为“解包运算符”或“扩展解包”运算符。
Inside Function Call 内部函数调用
Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments. Splat 将集合扩展为位置参数,而 splatty-splat 将字典扩展为关键字参数。
args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs)
Is the same as: 这是相同的:
func(1, 2, x=3, y=4, z=5)
Inside Function Definition 内部函数定义
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary. Splat 将零个或多个位置参数组合到一个元组中,而 splatty-splat 将零个或多个关键字参数组合到一个字典中。
def add(*a):
return sum(a)
>>> add(1, 2, 3)
6
Legal argument combinations: 合法的参数组合:
def f(*args): ... # f(1, 2, 3)
def f(x, *args): ... # f(1, 2, 3)
def f(*args, z): ... # f(1, 2, z=3)
def f(**kwargs): ... # f(x=1, y=2, z=3)
def f(x, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(*args, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(x, *args, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(*args, y, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(*, x, y, z): ... # f(x=1, y=2, z=3)
def f(x, *, y, z): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(x, y, *, z): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
Other Uses 其他用途
<list> = [*<coll.> [, ...]] # Or: list(<collection>) [+ ...]
<tuple> = (*<coll.>, [...]) # Or: tuple(<collection>) [+ ...]
<set> = {*<coll.> [, ...]} # Or: set(<collection>) [| ...]
<dict> = {**<dict> [, ...]} # Or: dict(<dict>) [| ...] (since 3.9)
head, *body, tail = <coll.> # Head or tail can be omitted.
#Inline 行内操作
Lambda 拉姆达
<func> = lambda: <return_value> # A single statement function.
<func> = lambda <arg_1>, <arg_2>: <return_value> # Also allows default arguments.
Comprehensions 推导式
<list> = [i+1 for i in range(10)] # Or: [1, 2, ..., 10]
<iter> = (i for i in range(10) if i > 5) # Or: iter([6, 7, 8, 9])
<set> = {i+5 for i in range(10)} # Or: {5, 6, ..., 14}
<dict> = {i: i*2 for i in range(10)} # Or: {0: 0, 1: 2, ..., 9: 18}
>>> [l+r for l in 'abc' for r in 'abc'] # Inner loop is on the right side.
['aa', 'ab', 'ac', ..., 'cc']
Map, Filter, Reduce 映射、过滤、归并
from functools import reduce
<iter> = map(lambda x: x + 1, range(10)) # Or: iter([1, 2, ..., 10])
<iter> = filter(lambda x: x > 5, range(10)) # Or: iter([6, 7, 8, 9])
<obj> = reduce(lambda out, x: out + x, range(10)) # Or: 45
Any, All 任一、全都
<bool> = any(<collection>) # Is `bool(<el>)` True for any el?
<bool> = all(<collection>) # True for all? Also True if empty.
Conditional Expression 条件表达式
<obj> = <exp> if <condition> else <exp> # Only one expression is evaluated.
>>> [a if a else 'zero' for a in (0, 1, 2, 3)] # `any([0, '', [], None]) == False`
['zero', 1, 2, 3]
Named Tuple, Enum, Dataclass 命名元组、枚举、数据类
from collections import namedtuple
Point = namedtuple('Point', 'x y') # Creates a tuple's subclass.
point = Point(0, 0) # Returns its instance.
from enum import Enum
Direction = Enum('Direction', 'N E S W') # Creates an enum.
direction = Direction.N # Returns its member.
from dataclasses import make_dataclass
Player = make_dataclass('Player', ['loc', 'dir']) # Creates a class.
player = Player(point, direction) # Returns its instance.
#Imports 引入(库/模块/文件)
import <module> # 引入模块或 Imports a built-in or '<module>.py'.
import <package> # 引入库包或 Imports a built-in or '<package>/__init__.py'.
import <package>.<module> # 引入库包的一个模块或 Imports a built-in or '<package>/<module>.py'.
- Package is a collection of modules, but it can also define its own objects. 包是模块的集合,但它也可以定义自己的对象。
- On a filesystem this corresponds to a directory of Python files with an optional init script. 在文件系统上,这对应于带有可选初始化脚本的 Python 文件目录。
- Running
'import <package>'does not automatically provide access to the package's modules unless they are explicitly imported in its init script. 运行'import <package>'不会自动提供对包模块的访问,除非它们在其初始化脚本中显式导入。
#Closure 闭包
We have/get a closure in Python when: 在以下情况下,我们在 Python 中拥有/得到一个闭包:
- A nested function references a value of its enclosing function and then the enclosing function returns the nested function. 嵌套函数引用其封闭函数的值,然后封闭函数返回嵌套函数。
def get_multiplier(a):
def out(b):
return a * b
return out
>>> multiply_by_3 = get_multiplier(3)
>>> multiply_by_3(10)
30
- If multiple nested functions within enclosing function reference the same value, that value gets shared. 如果封闭函数内的多个嵌套函数引用相同的值,则该值将被共享。
- To dynamically access function's first free variable use
'<function>.__closure__[0].cell_contents'. 要动态访问函数的第一个自由变量,请使用'<function>.__closure__[0].cell_contents'。
Partial 部分的
from functools import partial
<function> = partial(<function> [, <arg_1>, <arg_2>, ...])
>>> def multiply(a, b):
... return a * b
>>> multiply_by_3 = partial(multiply, 3)
>>> multiply_by_3(10)
30
- Partial is also useful in cases when function needs to be passed as an argument because it enables us to set its arguments beforehand. 当函数需要作为参数传递时,Partial 也很有用,因为它使我们能够预先设置其参数。
- A few examples being:
'defaultdict(<func>)','iter(<func>, to_exc)'and dataclass's'field(default_factory=<func>)'. 几个例子是:'defaultdict(<func>)'、'iter(<func>, to_exc)'和数据类的'field(default_factory=<func>)'。
Non-Local 非局部
If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'. 如果变量被分配给作用域中的任何位置,则它被视为局部变量,除非它被声明为“全局”或“非局部”。
def get_counter():
i = 0
def out():
nonlocal i
i += 1
return i
return out
>>> counter = get_counter()
>>> counter(), counter(), counter()
(1, 2, 3)
#Decorator 装饰器
- A decorator takes a function, adds some functionality and returns it. 装饰器接受一个函数,添加一些功能并返回它。
- It can be any callable, but is usually implemented as a function that returns a closure. 它可以是任何可调用的,但通常作为返回闭包的函数来实现。
@decorator_name
def function_that_gets_passed_to_decorator():
...
Debugger Example 调试装饰器示例
Decorator that prints function's name every time the function is called. 每次调用函数时打印函数名称的装饰器。
from functools import wrapsdef debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return out@debug
def add(x, y):
return x + y
- Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out). Wraps 是一个辅助装饰器,它将传递的函数 (func) 的元数据复制到它正在包装 (out) 的函数。
- Without it,
'add.__name__'would return'out'. 如果没有它,'add.__name__'将返回'out'。
LRU Cache LRU缓存
Decorator that caches function's return values. All function's arguments must be hashable. 缓存函数返回值的装饰器。所有函数的参数都必须是可散列的。
from functools import lru_cache@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-2) + fib(n-1)
- Default size of the cache is 128 values. Passing
'maxsize=None'makes it unbounded. 缓存的默认大小为 128 个值。传递'maxsize=None'使其无界。 - CPython interpreter limits recursion depth to 1000 by default. To increase it use
'sys.setrecursionlimit(<depth>)'. CPython 解释器默认将递归深度限制为 1000。要增加它,请使用'sys.setrecursionlimit(<depth>)'。
Parametrized Decorator 参数化装饰器
A decorator that accepts arguments and returns a normal decorator that accepts a function. 接受参数并返回接受函数的普通装饰器的装饰器。
from functools import wrapsdef debug(print_result=False):
def decorator(func):
@wraps(func)
def out(*args, **kwargs):
result = func(*args, **kwargs)
print(func.__name__, result if print_result else '')
return result
return out
return decorator@debug(print_result=True)
def add(x, y):
return x + y
- Using only
'@debug'to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can however manually check if the argument they received is a function and act accordingly. 仅使用'@debug'来装饰 add() 函数在这里不起作用,因为调试将接收 add() 函数作为“print_result”参数。然而,装饰器可以手动检查他们收到的参数是否是一个函数并采取相应的行动。
#Class 类
class <name>:
def __init__(self, a):
self.a = a
def __repr__(self):
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'
def __str__(self):
return str(self.a) @classmethod
def get_class_name(cls):
return cls.__name__
- Return value of repr() should be unambiguous and of str() readable. repr() 的返回值应该是明确的并且 str() 的返回值应该是可读的。
- If only repr() is defined, it will also be used for str(). 如果只定义了repr(),它也将用于str()。
- Methods decorated with
'@staticmethod'do not receive 'self' nor 'cls' as their first arg. 用'@staticmethod'修饰的方法不会接收“self”或“cls”作为其第一个参数。
Expressions that call the str() method: 调用 str() 方法的表达式:
print(<el>)
f'{<el>}'
logging.warning(<el>)
csv.writer(<file>).writerow([<el>])
raise Exception(<el>)
Expressions that call the repr() method: 调用 repr() 方法的表达式:
print/str/repr([<el>])
print/str/repr({<el>: <el>})
f'{<el>!r}'
Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z(<el>))
>>> <el>
Constructor Overloading 构造函数重载
class <name>:
def __init__(self, a=None):
self.a = a
Inheritance 继承
class Person:
def __init__(self, name):
self.name = nameclass Employee(Person):
def __init__(self, name, staff_num):
super().__init__(name)
self.staff_num = staff_num
Multiple Inheritance 多重继承
class A: pass
class B: pass
class C(A, B): pass
MRO determines the order in which parent classes are traversed when searching for a method or an attribute: MRO决定了搜索方法或属性时遍历父类的顺序:
>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
Type Annotations 类型注释
- They add type hints to variables, arguments and functions (
'def f() -> <type>:'). 它们向变量、参数和函数添加类型提示('def f() -> <type>:')。 - Hints are used by type checkers like mypy, data validation libraries such as Pydantic and lately also by Cython compiler. However, they are not enforced by CPython interpreter. 提示由 mypy 等类型检查器、Pydantic 等数据验证库以及最近的 Cython 编译器使用。然而,它们不是由 CPython 解释器强制执行的。
from collections import abc<name>: <type> [| ...] [= <obj>] # `|` since 3.10.
<name>: list/set/abc.Iterable/abc.Sequence[<type>] [= <obj>] # Since 3.9.
<name>: dict/tuple[<type>, ...] [= <obj>] # Since 3.9.
Dataclass 数据类
Decorator that uses class variables to generate init(), repr() and eq() special methods. 使用类变量生成 init()、repr() 和 eq() 特殊方法的装饰器。
from dataclasses import dataclass, field, make_dataclass@dataclass(order=False, frozen=False)
class <class_name>:
<attr_name>: <type>
<attr_name>: <type> = <default_value>
<attr_name>: list/dict/set = field(default_factory=list/dict/set)
- Objects can be made sortable with
'order=True'and immutable with'frozen=True'. 可以使用'order=True'使对象可排序,使用'frozen=True'使对象不可变。 - For object to be hashable, all attributes must be hashable and 'frozen' must be True. 对于可散列的对象,所有属性都必须是可散列的,并且“冻结”必须为 True。
- Function field() is needed because
'<attr_name>: list = []'would make a list that is shared among all instances. Its 'default_factory' argument can be any callable. 需要使用 field() 函数,因为'<attr_name>: list = []'将创建一个在所有实例之间共享的列表。它的“default_factory”参数可以是任何可调用的。 - For attributes of arbitrary type use
'typing.Any'. 对于任意类型的属性,请使用'typing.Any'。
<class> = make_dataclass('<class_name>', <coll_of_attribute_names>)
<class> = make_dataclass('<class_name>', <coll_of_tuples>)
<tuple> = ('<attr_name>', <type> [, <default_value>])
Property 属性(装饰器)
Pythonic way of implementing getters and setters. 实现 getter 和 setter 的 Pythonic 方式。
class Person:
@property
def name(self):
return ' '.join(self._name) @name.setter
def name(self, value):
self._name = value.split()
>>> person = Person()
>>> person.name = '\t Guido van Rossum \n'
>>> person.name
'Guido van Rossum'
Slots 插槽
Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint. 将对象限制为“槽”中列出的属性的机制,减少了它们的内存占用。
class MyClassWithSlots:
__slots__ = ['a']
def __init__(self):
self.a = 1
Copy 复制
from copy import copy, deepcopy
<object> = copy/deepcopy(<object>)
#Duck Types #鸭子类型
A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type. 鸭子类型是一种隐式类型,它规定了一组特殊方法。定义了这些方法的任何对象都被视为该鸭子类型的成员。
Comparable 可比性
- If eq() method is not overridden, it returns
'id(self) == id(other)', which is the same as'self is other'. 如果 eq() 方法未被重写,它将返回'id(self) == id(other)',与'self is other'相同。 - That means all objects compare not equal by default. 这意味着默认情况下所有对象比较都不相等。
- Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented. 只有左侧对象调用了 eq() 方法,除非它返回 NotImplemented,在这种情况下,将参考右侧对象。如果两者都返回 NotImplemented,则返回 False。
- Ne() automatically works on any object that has eq() defined. Ne() 自动作用于定义了 eq() 的任何对象。
class MyComparable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
Hashable 可散列(哈希)性
- Hashable object needs both hash() and eq() methods and its hash value should never change. Hashable 对象需要 hash() 和 eq() 方法,并且其哈希值永远不应该改变。
- Hashable objects that compare equal must have the same hash value, meaning default hash() that returns
'id(self)'will not do. 比较相等的可哈希对象必须具有相同的哈希值,这意味着返回'id(self)'的默认 hash() 将不起作用。 - That is why Python automatically makes classes unhashable if you only implement eq(). 这就是为什么如果你只实现 eq(),Python 就会自动使类不可散列。
class MyHashable:
def __init__(self, a):
self._a = a
@property
def a(self):
return self._a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __hash__(self):
return hash(self.a)
Sortable 可排序性
- With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated. 使用“total_ordering”装饰器,您只需要提供 eq() 和 lt()、gt()、le() 或 ge() 特殊方法之一,其余的将自动生成。
- Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts. 函数sorted()和min()只需要lt()方法,而max()只需要gt()方法。但是,最好对它们全部进行定义,以免在其他情况下出现混淆。
- When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal. 当比较两个列表、字符串或数据类时,它们的值将按顺序进行比较,直到找到一对不相等的值。然后返回这两个值的比较。如果所有值都相等,则较短的序列被认为较小。
- For proper alphabetical order pass
'key=locale.strxfrm'to sorted() after running'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'. 为了获得正确的字母顺序,请在运行'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'后将'key=locale.strxfrm'传递给sorted()。
from functools import total_ordering@total_ordering
class MySortable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __lt__(self, other):
if isinstance(other, type(self)):
return self.a < other.a
return NotImplemented
Iterator 迭代器
- Any object that has methods next() and iter() is an iterator. 任何具有 next() 和 iter() 方法的对象都是迭代器。
- Next() should return next item or raise StopIteration exception. Next() 应该返回下一个项目或引发 StopIteration 异常。
- Iter() should return 'self'. Iter() 应该返回“self”。
class Counter:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
def __iter__(self):
return self
>>> counter = Counter()
>>> next(counter), next(counter), next(counter)
(1, 2, 3)
Python has many different iterator objects: Python 有许多不同的迭代器对象:
- Sequence iterators returned by the iter() function, such as list_iterator and set_iterator. iter()函数返回的序列迭代器,例如list_iterator和set_iterator。
- Objects returned by the itertools module, such as count, repeat and cycle. itertools模块返回的对象,例如count、repeat和cycle。
- Generators returned by the generator functions and generator expressions. 由生成器函数和生成器表达式返回的生成器。
- File objects returned by the open() function, etc. open() 函数返回的文件对象等
Callable 可调用性
- All functions and classes have a call() method, hence are callable. 所有函数和类都有 call() 方法,因此都是可调用的。
- When this cheatsheet uses
'<function>'as an argument, it actually means'<callable>'. 当此备忘单使用'<function>'作为参数时,它实际上意味着'<callable>'。
class Counter:
def __init__(self):
self.i = 0
def __call__(self):
self.i += 1
return self.i
>>> counter = Counter()
>>> counter(), counter(), counter()
(1, 2, 3)
Context Manager 上下文管理器
- With statements only work with objects that have enter() and exit() special methods. With 语句仅适用于具有 Enter() 和 exit() 特殊方法的对象。
- Enter() should lock the resources and optionally return an object. Enter() 应该锁定资源并可选择返回一个对象。
- Exit() should release the resources. Exit() 应该释放资源。
- Any exception that happens inside the with block is passed to the exit() method. with 块内发生的任何异常都会传递给 exit() 方法。
- The exit() method can suppress the exception by returning a true value. exit() 方法可以通过返回 true 值来抑制异常。
class MyOpen:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, exc_type, exception, traceback):
self.file.close()
>>> with open('test.txt', 'w') as file:
... file.write('Hello World!')
>>> with MyOpen('test.txt') as file:
... print(file.read())
Hello World!
#Iterable Duck Types #可迭代性的鸭子类型
Iterable 可迭代性
- Only required method is iter(). It should return an iterator of object's items. 唯一需要的方法是 iter()。它应该返回对象项目的迭代器。
- Contains() automatically works on any object that has iter() defined. Contains() 自动作用于定义了 iter() 的任何对象。
class MyIterable:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
>>> obj = MyIterable([1, 2, 3])
>>> [el for el in obj]
[1, 2, 3]
>>> 1 in obj
True
Collection 集合
- Only required methods are iter() and len(). Len() should return the number of items. 唯一需要的方法是 iter() 和 len()。 Len() 应返回项目数。
- This cheatsheet actually means
'<iterable>'when it uses'<collection>'. 当它使用'<collection>'时,这个备忘单实际上意味着'<iterable>'。 - I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. 我选择不使用“可迭代”这个名字,因为它听起来比“集合”更可怕、更模糊。 The only drawback of this decision is that the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections. 这个决定的唯一缺点是,读者可能会认为某个函数在接受迭代器时不接受迭代器,因为迭代器是唯一可迭代但不是集合的内置对象。
class MyCollection:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
Sequence 序列
- Only required methods are getitem() and len(). 唯一需要的方法是 getitem() 和 len()。
- Getitem() should return an item at the passed index or raise IndexError. Getitem() 应该在传递的索引处返回一个项目或引发 IndexError。
- Iter() and contains() automatically work on any object that has getitem() defined. Iter() 和 contains() 自动作用于定义了 getitem() 的任何对象。
- Reversed() automatically works on any object that has getitem() and len() defined. Reversed() 自动作用于定义了 getitem() 和 len() 的任何对象。
class MySequence:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
def __reversed__(self):
return reversed(self.a)
Discrepancies between glossary definitions and abstract base classes: 术语表定义和抽象基类之间的差异:
- Glossary defines iterable as any object with iter() or getitem() and sequence as any object with getitem() and len(). It does not define collection. 术语表将可迭代定义为具有 iter() 或 getitem() 的任何对象,将序列定义为具有 getitem() 和 len() 的任何对象。它没有定义集合。
- Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has method iter(), while ABC Collection checks for iter(), contains() and len(). 将 ABC Iterable 传递给 isinstance() 或 issubclass() 检查对象/类是否具有 iter() 方法,而 ABC Collection 检查 iter()、contains() 和 len()。
ABC Sequence ABC 序列
- It's a richer interface than the basic sequence. 它是一个比基本序列更丰富的界面。
- Extending it generates iter(), contains(), reversed(), index() and count(). 扩展它会生成 iter()、contains()、reverse()、index() 和 count()。
- Unlike
'abc.Iterable'and'abc.Collection', it is not a duck type. That is why'issubclass(MySequence, abc.Sequence)'would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, array, memoryview and deque, because they are registered as its virtual subclasses. 与'abc.Iterable'和'abc.Collection'不同,它不是鸭子类型。这就是为什么即使 MySequence 定义了所有方法,'issubclass(MySequence, abc.Sequence)'也会返回 False。然而,它可以识别列表、元组、范围、str、字节、字节数组、数组、内存视图和双端队列,因为它们被注册为其虚拟子类。
from collections import abcclass MyAbcSequence(abc.Sequence):
def __init__(self, a):
self.a = a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
Table of required and automatically available special methods: 所需的和自动可用的特殊方法表:
┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┃ │ Iterable │ Collection │ Sequence │ abc.Sequence ┃
┠────────────┼────────────┼────────────┼────────────┼──────────────┨
┃ iter() │ ! │ ! │ ✓ │ ✓ ┃
┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ len() │ │ ! │ ! │ ! ┃
┃ getitem() │ │ │ ! │ ! ┃
┃ reversed() │ │ │ ✓ │ ✓ ┃
┃ index() │ │ │ │ ✓ ┃
┃ count() │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
- Method iter() is required for
'isinstance(<obj>, abc.Iterable)'to return True, however any object with getitem() will work just fine with any code expecting an iterable.'isinstance(<obj>, abc.Iterable)'需要方法 iter() 才能返回 True,但是任何具有 getitem() 的对象都可以与任何需要可迭代的代码一起正常工作。 - Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping. 扩展时生成缺失方法的抽象基类有:Sequence、MutableSequence、Set、MutableSet、Mapping 和 MutableMapping。
- Names of their required methods are stored in
'<abc>.__abstractmethods__'. 它们所需方法的名称存储在'<abc>.__abstractmethods__'中。
#Enum 枚举
from enum import Enum, auto
class <enum_name>(Enum):
<member_name> = auto()
<member_name> = <value>
<member_name> = <value>, <value>
- Function auto() returns an increment of the last numeric value or 1. 函数 auto() 返回最后一个数值的增量或 1。
- Accessing a member named after a reserved keyword causes SyntaxError. 访问以保留关键字命名的成员会导致语法错误。
- Methods receive the member they were called on as the 'self' argument. 方法接收它们被调用的成员作为“self”参数。
<member> = <enum>.<member_name> # Returns a member.
<member> = <enum>['<member_name>'] # Returns a member. Raises KeyError.
<member> = <enum>(<value>) # Returns a member. Raises ValueError.
<str> = <member>.name # Returns member's name.
<obj> = <member>.value # Returns member's value.
<list> = list(<enum>) # Returns enum's members.
<list> = [a.name for a in <enum>] # Returns enum's member names.
<list> = [a.value for a in <enum>] # Returns enum's member values.
<enum> = type(<member>) # Returns member's enum.
<iter> = itertools.cycle(<enum>) # Retruns endless iterator of members.
<member> = random.choice(list(<enum>)) # Returns a random member.
Inline 行内枚举
Cutlery = Enum('Cutlery', 'FORK KNIFE SPOON')
Cutlery = Enum('Cutlery', ['FORK', 'KNIFE', 'SPOON'])
Cutlery = Enum('Cutlery', {'FORK': 1, 'KNIFE': 2, 'SPOON': 3})
User-defined functions cannot be values, so they must be wrapped: 用户定义的函数不能是值,因此必须将它们包装起来:
from functools import partial
LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
'OR': partial(lambda l, r: l or r)})
#Exceptions 异常
try:
<code>
except <exception>:
<code>
Complex Example 复杂的例子
try:
<code_1>
except <exception_a>:
<code_2_a>
except <exception_b>:
<code_2_b>
else:
<code_2_c>
finally:
<code_3>
- Code inside the
'else'block will only be executed if'try'block had no exceptions. 仅当'try'块没有异常时才会执行'else'块内的代码。 - Code inside the
'finally'block will always be executed (unless a signal is received).'finally'块内的代码将始终被执行(除非收到信号)。 - All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try/except clause (only function block delimits scope). 在执行块中初始化的所有变量在所有后续块以及 try/ except 子句之外都可见(仅功能块界定范围)。
- To catch signals use
'signal.signal(signal_number, <func>)'. 要捕获信号,请使用'signal.signal(signal_number, <func>)'。
Catching Exceptions 捕获异常
except <exception>: ...
except <exception> as <name>: ...
except (<exception>, [...]): ...
except (<exception>, [...]) as <name>: ...
- Also catches subclasses of the exception. 还捕获异常的子类。
- Use
'traceback.print_exc()'to print the full error message to stderr. 使用'traceback.print_exc()'将完整的错误消息打印到 stderr。 - Use
'print(<name>)'to print just the cause of the exception (its arguments). 使用'print(<name>)'仅打印异常的原因(其参数)。 - Use
'logging.exception(<message>)'to log the passed message, followed by the full error message of the caught exception. 使用'logging.exception(<message>)'记录传递的消息,后跟捕获的异常的完整错误消息。 - Use
'sys.exc_info()'to get exception type, object and traceback of caught exception. 使用'sys.exc_info()'获取异常类型、对象和捕获异常的回溯。
Raising Exceptions 引发异常
raise <exception>
raise <exception>()
raise <exception>(<el> [, ...])
Re-raising caught exception: 重新引发捕获异常:
except <exception> [as <name>]:
...
raise
Exception Object 异常对象
arguments = <name>.args
exc_type = <name>.__class__
filename = <name>.__traceback__.tb_frame.f_code.co_filename
func_name = <name>.__traceback__.tb_frame.f_code.co_name
line = linecache.getline(filename, <name>.__traceback__.tb_lineno)
trace_str = ''.join(traceback.format_tb(<name>.__traceback__))
error_msg = ''.join(traceback.format_exception(type(<name>), <name>, <name>.__traceback__))
Built-in Exceptions 内置异常
BaseException
├── SystemExit # 由 sys.exit() 函数引发。 | Raised by the sys.exit() function.
├── KeyboardInterrupt # 当用户按下中断键 (ctrl-c) 时引发。 | Raised when the user hits the interrupt key (ctrl-c).
└── Exception # 用户定义的异常应该从此类派生。 | User-defined exceptions should be derived from this class.
├── ArithmeticError # 算术错误(例如 ZeroDivisionError)的基类。 | Base class for arithmetic errors such as ZeroDivisionError.
├── AssertionError # 如果表达式返回 false 值,则由 `assert <exp>` 引发。 | Raised by `assert <exp>` if expression returns false value.
├── AttributeError # 当对象没有请求的属性/方法时引发。 | Raised when object doesn't have requested attribute/method.
├── EOFError # 当遇到文件结束条件时由 input() 引发。 | Raised by input() when it hits an end-of-file condition.
├── LookupError # 当集合找不到项目时出现错误的基类。 | Base class for errors when a collection can't find an item.
│ ├── IndexError # 当序列索引超出范围时引发。 | Raised when a sequence index is out of range.
│ └── KeyError # 当字典键或集合元素丢失时引发。 | Raised when a dictionary key or set element is missing.
├── MemoryError # 内存不足。开始删除变量可能为时已晚。 | Out of memory. Could be too late to start deleting vars.
├── NameError # 当使用不存在的名称(变量/函数/类)时引发。 | Raised when nonexistent name (variable/func/class) is used.
│ └── UnboundLocalError # 在定义本地名称之前使用本地名称时引发。 | Raised when local name is used before it's being defined.
├── OSError # 诸如 FileExistsError/TimeoutError 之类的错误(请参阅#Open)。 | Errors such as FileExistsError/TimeoutError (see #Open).
│ └── ConnectionError # BrokenPipeError/ConnectionAbortedError 等错误。 | Errors such as BrokenPipeError/ConnectionAbortedError.
├── RuntimeError # 由不属于其他类别的错误引发。 | Raised by errors that don't fall into other categories.
│ ├── NotImplementedEr… # 可以通过抽象方法或未完成的代码引发。 | Can be raised by abstract methods or by unfinished code.
│ └── RecursionError # 当超过最大递归深度时引发。 | Raised when the maximum recursion depth is exceeded.
├── StopIteration # 当空迭代器传递给 next() 时引发。 | Raised when an empty iterator is passed to next().
├── TypeError # 当错误类型的参数传递给函数时。 | When an argument of the wrong type is passed to function.
└── ValueError # 当参数具有正确的类型但不适当的值时。 | When argument has the right type but inappropriate value.
Collections and their exceptions: 集合及其例外:
┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┃ │ List │ Set │ Dict ┃
┠───────────┼────────────┼────────────┼────────────┨
┃ getitem() │ IndexError │ │ KeyError ┃
┃ pop() │ IndexError │ KeyError │ KeyError ┃
┃ remove() │ ValueError │ KeyError │ ┃
┃ index() │ ValueError │ │ ┃
┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
Useful built-in exceptions: 有用的内置异常:
raise TypeError('Argument is of the wrong type!')
raise ValueError('Argument has the right type but an inappropriate value!')
raise RuntimeError('I am too lazy to define my own exception!')
User-defined Exceptions 用户定义的异常
class MyError(Exception): pass
class MyInputError(MyError): pass
#Exit 退出
Exits the interpreter by raising SystemExit exception. 通过引发 SystemExit 异常退出解释器。
import sys
sys.exit() # Exits with exit code 0 (success).
sys.exit(<el>) # Prints to stderr and exits with 1.
sys.exit(<int>) # Exits with the passed exit code.
#Print 打印
print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
- Use
'file=sys.stderr'for messages about errors. 使用'file=sys.stderr'获取有关错误的消息。 - Stdout and stderr streams hold output in a buffer until they receive a string containing '\n' or '\r', buffer reaches 4096 characters,
'flush=True'is used, or program exits. Stdout 和 stderr 流将输出保存在缓冲区中,直到它们收到包含 '\n' 或 '\r' 的字符串、缓冲区达到 4096 个字符、使用'flush=True'或程序退出。
Pretty Print 美化打印
from pprint import pprint
pprint(<collection>, width=80, depth=None, compact=False, sort_dicts=True)
- Each item is printed on its own line if collection takes up more than 'width' characters. 如果集合占用的字符数超过“宽度”,则每个项目将打印在自己的行上。
- Nested collections that are 'depth' levels deep get printed as '…'. “深度”级别的嵌套集合将打印为“...”。
#Input (命令行)输入
<str> = input(prompt=None)
- Reads a line from the user input or pipe if present (trailing newline gets stripped). 从用户输入或管道中读取一行(如果存在)(尾随换行符被删除)。
- Prompt string is printed to the standard output before reading input. 在读取输入之前,将提示字符串打印到标准输出。
- Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted. 当用户点击 EOF (ctrl-d/ctrl-z⏎) 或输入流耗尽时引发 EOFError。
#Command Line Arguments #命令行参数
import sys
scripts_path = sys.argv[0]
arguments = sys.argv[1:]
Argument Parser 参数解析器
from argparse import ArgumentParser, FileType
p = ArgumentParser(description=<str>) # Returns a parser.
p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag (defaults to False).
p.add_argument('-<short_name>', '--<name>', type=<type>) # Option (defaults to None).
p.add_argument('<name>', type=<type>, nargs=1) # Mandatory first argument.
p.add_argument('<name>', type=<type>, nargs='+') # Mandatory remaining args.
p.add_argument('<name>', type=<type>, nargs='*') # Optional arguments.
<args> = p.parse_args() # Exits on parsing error.
<obj> = <args>.<name> # Returns `<type>(<arg>)`.
- Use
'help=<str>'to set argument description that will be displayed in help message. 使用'help=<str>'设置将在帮助消息中显示的参数描述。 - Use
'default=<el>'to set option's default value. 使用'default=<el>'设置选项的默认值。 - Use
'type=FileType(<mode>)'for files. Accepts 'encoding', but 'newline' is None. 对文件使用'type=FileType(<mode>)'。接受“编码”,但“换行符”为“无”。
#Open 打开文件
Opens the file and returns a corresponding file object. 打开文件并返回相应的文件对象。
<file> = open(<path>, mode='r', encoding=None, newline=None)
'encoding=None'means that the default encoding is used, which is platform dependent. Best practice is to use'encoding="utf-8"'whenever possible.'encoding=None'表示使用默认编码,该编码与平台相关。最佳实践是尽可能使用'encoding="utf-8"'。'newline=None'means all different end of line combinations are converted to '\n' on read, while on write all '\n' characters are converted to system's default line separator.'newline=None'表示所有不同的行尾组合在读取时都会转换为“\n”,而在写入时所有“\n”字符都会转换为系统的默认行分隔符。'newline=""'means no conversions take place, but input is still broken into chunks by readline() and readlines() on every '\n', '\r' and '\r\n'.'newline=""'表示不发生任何转换,但输入仍然被 readline() 和 readlines() 在每个 '\n'、'\r' 和 '\r\n' 上分成块。
Modes 文件读写模式
'r'- Read (default).'r'- 读取(默认)。'w'- Write (truncate).'w'- 写入(截断)。'x'- Write or fail if the file already exists.'x'- 如果文件已存在,则写入或失败。'a'- Append.'a'- 追加。'w+'- Read and write (truncate).'w+'- 读取和写入(截断)。'r+'- Read and write from the start.'r+'- 从头开始读取和写入。'a+'- Read and write from the end.'a+'- 从末尾开始读取和写入。'b'- Binary mode ('br','bw','bx', …).'b'- 二进制模式('br'、'bw'、'bx'、...)。
Exceptions 例外情况
'FileNotFoundError'can be raised when reading with'r'or'r+'. 使用'r'或'r+'读取时可以引发'FileNotFoundError'。'FileExistsError'can be raised when writing with'x'. 使用'x'写入时可以引发'FileExistsError'。'IsADirectoryError'and'PermissionError'can be raised by any.'IsADirectoryError'和'PermissionError'可以由任何一个引发。'OSError'is the parent class of all listed exceptions.'OSError'是所有列出的异常的父类。
File Object 文件对象
<file>.seek(0) # Moves to the start of the file.
<file>.seek(offset) # Moves 'offset' chars/bytes from the start.
<file>.seek(0, 2) # Moves to the end of the file.
<bin_file>.seek(±offset, <anchor>) # Anchor: 0 start, 1 current position, 2 end.
<str/bytes> = <file>.read(size=-1) # Reads 'size' chars/bytes or until EOF.
<str/bytes> = <file>.readline() # Returns a line or empty string/bytes on EOF.
<list> = <file>.readlines() # Returns a list of remaining lines.
<str/bytes> = next(<file>) # Returns a line using buffer. Do not mix.
<file>.write(<str/bytes>) # Writes a string or bytes object.
<file>.writelines(<collection>) # Writes a coll. of strings or bytes objects.
<file>.flush() # Flushes write buffer. Runs every 4096/8192 B.
<file>.close() # Closes the file after flushing.
- Methods do not add or strip trailing newlines, not even writelines(). 方法不会添加或删除尾随换行符,甚至 writelines() 也不会。
Read Text from File 从文件中读取文本
def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines()
Write Text to File 将文本写入文件
def write_to_file(filename, text):
with open(filename, 'w', encoding='utf-8') as file:
file.write(text)
#Paths 路径
import os, glob
from pathlib import Path
<str> = os.getcwd() # Returns the current working directory.
<str> = os.path.join(<path>, ...) # Joins two or more pathname components.
<str> = os.path.realpath(<path>) # Resolves symlinks and calls path.abspath().
<str> = os.path.basename(<path>) # Returns final component of the path.
<str> = os.path.dirname(<path>) # Returns path without the final component.
<tup.> = os.path.splitext(<path>) # Splits on last period of the final component.
<list> = os.listdir(path='.') # Returns filenames located at the path.
<list> = glob.glob('<pattern>') # Returns paths matching the wildcard pattern.
<bool> = os.path.exists(<path>) # Or: <Path>.exists()
<bool> = os.path.isfile(<path>) # Or: <DirEntry/Path>.is_file()
<bool> = os.path.isdir(<path>) # Or: <DirEntry/Path>.is_dir()
<stat> = os.stat(<path>) # Or: <DirEntry/Path>.stat()
<real> = <stat>.st_mtime/st_size/… # Modification time, size in bytes, ...
DirEntry 目录项
Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it. 与 listdir() 不同,scandir() 返回 DirEntry 对象,该对象缓存 isfile、isdir 以及 Windows 上的统计信息,从而显着提高需要它的代码的性能。
<iter> = os.scandir(path='.') # Returns DirEntry objects located at the path.
<str> = <DirEntry>.path # Returns the whole path as a string.
<str> = <DirEntry>.name # Returns final component as a string.
<file> = open(<DirEntry>) # Opens the file and returns a file object.
Path Object 路径对象
<Path> = Path(<path> [, ...]) # Accepts strings, Paths and DirEntry objects.
<Path> = <path> / <path> [/ ...] # First or second path must be a Path object.
<Path> = <Path>.resolve() # Returns absolute path with resolved symlinks.
<Path> = Path() # Returns relative cwd. Also Path('.').
<Path> = Path.cwd() # Returns absolute cwd. Also Path().resolve().
<Path> = Path.home() # Returns user's home directory (absolute).
<Path> = Path(__file__).resolve() # Returns script's path if cwd wasn't changed.
<Path> = <Path>.parent # Returns Path without the final component.
<str> = <Path>.name # Returns final component as a string.
<str> = <Path>.stem # Returns final component without extension.
<str> = <Path>.suffix # Returns final component's extension.
<tup.> = <Path>.parts # Returns all components as strings.
<iter> = <Path>.iterdir() # Returns directory contents as Path objects.
<iter> = <Path>.glob('<pattern>') # Returns Paths matching the wildcard pattern.
<str> = str(<Path>) # Returns path as a string.
<file> = open(<Path>) # Also <Path>.read/write_text/bytes().
#OS Commands #操作系统命令
import os, shutil, subprocess
os.chdir(<path>) # Changes the current working directory.
os.mkdir(<path>, mode=0o777) # Creates a directory. Permissions are in octal.
os.makedirs(<path>, mode=0o777) # Creates all path's dirs. Also `exist_ok=False`.
shutil.copy(from, to) # Copies the file. 'to' can exist or be a dir.
shutil.copy2(from, to) # Also copies creation and modification time.
shutil.copytree(from, to) # Copies the directory. 'to' must not exist.
os.rename(from, to) # Renames/moves the file or directory.
os.replace(from, to) # Same, but overwrites file 'to' even on Windows.
shutil.move(from, to) # Rename() that moves into 'to' if it's a dir.
os.remove(<path>) # Deletes the file.
os.rmdir(<path>) # Deletes the empty directory.
shutil.rmtree(<path>) # Deletes the directory.
- Paths can be either strings, Paths or DirEntry objects. 路径可以是字符串、Paths 或 DirEntry 对象。
- Functions report OS related errors by raising either OSError or one of its subclasses. 函数通过引发 OSError 或其子类之一来报告操作系统相关错误。
Shell Commands Shell命令
<pipe> = os.popen('<command>') # Executes command in sh/cmd. Returns its stdout pipe.
<str> = <pipe>.read(size=-1) # Reads 'size' chars or until EOF. Also readline/s().
<int> = <pipe>.close() # Closes the pipe. Returns None on success (returncode 0).
Sends '1 + 1' to the basic calculator and captures its output: 将“1 + 1”发送到基本计算器并捕获其输出:
>>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True)
CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
Sends test.in to the basic calculator running in standard mode and saves its output to test.out: 将 test.in 发送到在标准模式下运行的基本计算器,并将其输出保存到 test.out:
>>> from shlex import split
>>> os.popen('echo 1 + 1 > test.in')
>>> subprocess.run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
CompletedProcess(args=['bc', '-s'], returncode=0)
>>> open('test.out').read()
'2\n'
#JSON
Text file format for storing collections of strings and numbers. 用于存储字符串和数字集合的文本文件格式。
import json
<str> = json.dumps(<object>) # Converts object to JSON string.
<object> = json.loads(<str>) # Converts JSON string to object.
Read Object from JSON File 从 JSON 文件读取对象
def read_json_file(filename):
with open(filename, encoding='utf-8') as file:
return json.load(file)
Write Object to JSON File 将对象写入 JSON 文件
def write_to_json_file(filename, an_object):
with open(filename, 'w', encoding='utf-8') as file:
json.dump(an_object, file, ensure_ascii=False, indent=2)
#Pickle (一种二进制文件格式)
Binary file format for storing Python objects. 用于存储 Python 对象的二进制文件格式。
import pickle
<bytes> = pickle.dumps(<object>) # Converts object to bytes object.
<object> = pickle.loads(<bytes>) # Converts bytes object to object.
Read Object from File 从文件中读取对象
def read_pickle_file(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
Write Object to File 将对象写入文件
def write_to_pickle_file(filename, an_object):
with open(filename, 'wb') as file:
pickle.dump(an_object, file)
#CSV 电子表格的文本
Text file format for storing spreadsheets. 用于存储电子表格的文本文件格式。
import csv
Read 读
<reader> = csv.reader(<file>) # Also: `dialect='excel', delimiter=','`.
<list> = next(<reader>) # Returns next row as a list of strings.
<list> = list(<reader>) # Returns a list of remaining rows.
- File must be opened with a
'newline=""'argument, or newlines embedded inside quoted fields will not be interpreted correctly! 文件必须使用'newline=""'参数打开,否则嵌入在引用字段中的换行符将无法正确解释! - To print the spreadsheet to the console use Tabulate library. 要将电子表格打印到控制台,请使用 Tabulate 库。
- For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library. 对于 XML 和二进制 Excel 文件(xlsx、xlsm 和 xlsb),请使用 Pandas 库。
- Reader accepts any iterator of strings, not just files. Reader 接受任何字符串迭代器,而不仅仅是文件。
Write 写
<writer> = csv.writer(<file>) # Also: `dialect='excel', delimiter=','`.
<writer>.writerow(<collection>) # Encodes objects using `str(<el>)`.
<writer>.writerows(<coll_of_coll>) # Appends multiple rows.
- File must be opened with a
'newline=""'argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings! 文件必须使用'newline=""'参数打开,否则在使用 '\r\n' 行结尾的平台上,'\r' 将添加到每个 '\n' 前面! - Open existing file with
'mode="w"'to overwrite it or'mode="a"'to append to it. 使用'mode="w"'打开现有文件以覆盖它,或使用'mode="a"'附加到它。
Parameters 参数
'dialect'- Master parameter that sets the default values. String or a 'csv.Dialect' object.'dialect'- 设置默认值的主参数。字符串或“csv.Dialect”对象。'delimiter'- A one-character string used to separate fields.'delimiter'- 用于分隔字段的单字符字符串。'quotechar'- Character for quoting fields that contain special characters.'quotechar'- 用于引用包含特殊字符的字段的字符。'doublequote'- Whether quotechars inside fields are/get doubled or escaped.'doublequote'- 字段内的引号字符是否加倍或转义。'skipinitialspace'- Is space character at the start of the field stripped by the reader.'skipinitialspace'- 字段开头的空格字符被读取器删除。'lineterminator'- How writer terminates rows. Reader is hardcoded to '\n', '\r', '\r\n'.'lineterminator'- writer 如何终止行。 Reader 被硬编码为 '\n'、'\r'、'\r\n'。'quoting'- 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.'quoting'- 0:根据需要,1:全部,2:除了读取为浮点数的数字之外的所有内容,3:无。'escapechar'- Character for escaping quotechars if 'doublequote' is False.'escapechar'- 如果 'doublequote' 为 False,则转义引号字符。
Dialects 方言
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┃ │ excel │ excel-tab │ unix ┃
┠──────────────────┼──────────────┼──────────────┼──────────────┨
┃ delimiter │ ',' │ '\t' │ ',' ┃
┃ quotechar │ '"' │ '"' │ '"' ┃
┃ doublequote │ True │ True │ True ┃
┃ skipinitialspace │ False │ False │ False ┃
┃ lineterminator │ '\r\n' │ '\r\n' │ '\n' ┃
┃ quoting │ 0 │ 0 │ 1 ┃
┃ escapechar │ None │ None │ None ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
Read Rows from CSV File 从 CSV 文件中读取行
def read_csv_file(filename, dialect='excel', **params):
with open(filename, encoding='utf-8', newline='') as file:
return list(csv.reader(file, dialect, **params))
Write Rows to CSV File 将行写入 CSV 文件
def write_to_csv_file(filename, rows, mode='w', dialect='excel', **params):
with open(filename, mode, encoding='utf-8', newline='') as file:
writer = csv.writer(file, dialect, **params)
writer.writerows(rows)
#SQLite
A server-less database engine that stores each database into a separate file. 将每个数据库存储到单独文件中的无服务器数据库引擎。
import sqlite3
<conn> = sqlite3.connect(<path>) # Opens existing or new file. Also ':memory:'.
<conn>.close() # Closes the connection.
Read 读
<cursor> = <conn>.execute('<query>') # Can raise a subclass of sqlite3.Error.
<tuple> = <cursor>.fetchone() # Returns next row. Also next(<cursor>).
<list> = <cursor>.fetchall() # Returns remaining rows. Also list(<cursor>).
Write 写
<conn>.execute('<query>') # Can raise a subclass of sqlite3.Error.
<conn>.commit() # Saves all changes since the last commit.
<conn>.rollback() # Discards all changes since the last commit.
Or: 或者:
with <conn>: # Exits the block with commit() or rollback(),
<conn>.execute('<query>') # depending on whether any exception occurred.
Placeholders 占位符
<conn>.execute('<query>', <list/tuple>) # Replaces '?'s in query with values.
<conn>.execute('<query>', <dict/namedtuple>) # Replaces ':<key>'s with values.
<conn>.executemany('<query>', <coll_of_above>) # Runs execute() multiple times.
- Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime. 传递的值可以是 str、int、float、bytes、None、bool、datetime.date 或 datetime.datetime 类型。
- Bools will be stored and returned as ints and dates as ISO formatted strings. 布尔值将以整数形式存储和返回,日期以 ISO 格式的字符串形式存储和返回。
Example 例子
Values are not actually saved in this example because 'conn.commit()' is omitted!
此示例中实际上并未保存值,因为省略了 'conn.commit()' !
>>> conn = sqlite3.connect('test.db')
>>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
>>> conn.execute('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid
1
>>> conn.execute('SELECT * FROM person').fetchall()
[(1, 'Jean-Luc', 187)]
SqlAlchemy 一种数据库ORM
# $ pip3 install sqlalchemy
from sqlalchemy import create_engine, text
<engine> = create_engine('<url>') # Url: 'dialect://user:password@host/dbname'.
<conn> = <engine>.connect() # Creates a connection. Also <conn>.close().
<cursor> = <conn>.execute(text('<query>'), …) # Replaces ':<key>'s with keyword arguments.
with <conn>.begin(): ... # Exits the block with commit or rollback.
┏━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Dialect │ pip3 install │ import │ Dependencies ┃
┠────────────┼──────────────┼──────────┼──────────────────────────────────┨
┃ mysql │ mysqlclient │ MySQLdb │ www.pypi.org/project/mysqlclient ┃
┃ postgresql │ psycopg2 │ psycopg2 │ www.pypi.org/project/psycopg2 ┃
┃ mssql │ pyodbc │ pyodbc │ www.pypi.org/project/pyodbc ┃
┃ oracle │ oracledb │ oracledb │ www.pypi.org/project/oracledb ┃
┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
#Bytes 比特
Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray. Bytes 对象是一个不可变的单字节序列。可变版本称为字节数组。
<bytes> = b'<str>' # Only accepts ASCII characters and \x00-\xff.
<int> = <bytes>[<index>] # Returns an int in range from 0 to 255.
<bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes as a separator.
Encode 编码
<bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
<bytes> = bytes(<str>, 'utf-8') # Or: <str>.encode('utf-8')
<bytes> = <int>.to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`.
<bytes> = bytes.fromhex('<hex>') # Hex pairs can be separated by whitespaces.
Decode 解码
<list> = list(<bytes>) # Returns ints in range from 0 to 255.
<str> = str(<bytes>, 'utf-8') # Or: <bytes>.decode('utf-8')
<int> = int.from_bytes(<bytes>, …) # `byteorder='big/little', signed=False`.
'<hex>' = <bytes>.hex() # Returns hex pairs. Accepts `sep=<str>`.
Read Bytes from File 从文件中读取字节
def read_bytes(filename):
with open(filename, 'rb') as file:
return file.read()
Write Bytes to File 将字节写入文件
def write_bytes(filename, bytes_obj):
with open(filename, 'wb') as file:
file.write(bytes_obj)
#Struct 结构
- Module that performs conversions between a sequence of numbers and a bytes object. 在数字序列和字节对象之间执行转换的模块。
- System’s type sizes, byte order, and alignment rules are used by default. 默认情况下使用系统的类型大小、字节顺序和对齐规则。
from struct import pack, unpack
<bytes> = pack('<format>', <el_1> [, ...]) # Packages arguments or raises struct.error.
<tuple> = unpack('<format>', <bytes>) # Use iter_unpack() for iterator of tuples.
>>> pack('>hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
Format 格式
For standard type sizes and manual alignment (padding) start format string with: 对于标准字体大小和手动对齐(填充),起始格式字符串为:
'='- System's byte order (usually little-endian).'='- 系统的字节顺序(通常是小端)。'<'- Little-endian (i.e. least significant byte first).'<'- Little-endian(即最低有效字节在前)。'>'- Big-endian (also'!').'>'- 大尾数(也为'!')。
Besides numbers, pack() and unpack() also support bytes objects as part of the sequence: 除了数字之外,pack() 和 unpack() 还支持字节对象作为序列的一部分:
'c'- A bytes object with a single element. For pad byte use'x'.'c'- 具有单个元素的字节对象。对于填充字节,请使用'x'。'<n>s'- A bytes object with n elements (not effected by byte order).'<n>s'- 具有 n 个元素的字节对象(不受字节顺序影响)。
Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets: 整数类型。对于无符号类型使用大写字母。最小和标准尺寸在括号中:
'b'- char (1/1)'b'- 字符 (1/1)'h'- short (2/2)'h'- 短 (2/2)'i'- int (2/4)'i'- 整数 (2/4)'l'- long (4/4)'l'- 长 (4/4)'q'- long long (8/8)'q'- 长长 (8/8)
Floating point types (struct always uses standard sizes): 浮点类型(结构体始终使用标准大小):
'f'- float (4/4)'f'- 浮动 (4/4)'d'- double (8/8)'d'- 双 (8/8)
#Array 阵列
List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method. 只能保存预定义类型的数字的列表。上面列出了可用类型及其最小大小(以字节为单位)。类型大小和字节顺序始终由系统确定,但是每个元素的字节可以使用 byteswap() 方法进行交换。
from array import array
<array> = array('<typecode>', <collection>) # Array from collection of numbers.
<array> = array('<typecode>', <bytes>) # Array from bytes object.
<array> = array('<typecode>', <array>) # Treats array as a sequence of numbers.
<array>.fromfile(<file>, n_items) # Appends items. Raises EOFError on end.
<bytes> = bytes(<array>) # Or: <array>.tobytes()
<file>.write(<array>) # Writes array to the binary file.
#Memory View #内存视图
- A sequence object that points to the memory of another bytes-like object. 指向另一个类似字节对象的内存的序列对象。
- Each element can reference a single or multiple consecutive bytes, depending on format. 每个元素可以引用单个或多个连续字节,具体取决于格式。
- Order and number of elements can be changed with slicing. 元素的顺序和数量可以通过切片来更改。
- Casting only works between char and other types and uses system's sizes. 转换仅适用于 char 和其他类型之间,并使用系统的大小。
- Byte order is always determined by the system. 字节顺序始终由系统决定。
<mview> = memoryview(<bytes/bytearray/array>) # Immutable if bytes, else mutable.
<real> = <mview>[<index>] # Returns an int or a float.
<mview> = <mview>[<slice>] # Mview with rearranged elements.
<mview> = <mview>.cast('<typecode>') # Casts memoryview to the new format.
<mview>.release() # Releases the object's memory buffer.
<bytes> = bytes(<mview>) # Returns a new bytes object.
<bytes> = <bytes>.join(<coll_of_mviews>) # Joins mviews using bytes object as sep.
<array> = array('<typecode>', <mview>) # Treats mview as a sequence of numbers.
<file>.write(<mview>) # Writes mview to the binary file.
<list> = list(<mview>) # Returns a list of ints or floats.
<str> = str(<mview>, 'utf-8') # Treats mview as a bytes object.
<int> = int.from_bytes(<mview>, …) # `byteorder='big/little', signed=False`.
'<hex>' = <mview>.hex() # Treats mview as a bytes object.
#Deque
A thread-safe list with efficient appends and pops from either side. Pronounced "deck". 一个线程安全的列表,可以从任意一侧进行高效的追加和弹出操作。发音为“甲板”。
from collections import deque
<deque> = deque(<collection>) # Also `maxlen=None`.
<deque>.appendleft(<el>) # Opposite element is dropped if full.
<deque>.extendleft(<collection>) # Collection gets reversed.
<el> = <deque>.popleft() # Raises IndexError if empty.
<deque>.rotate(n=1) # Rotates elements to the right.
#Threading 线程
CPython interpreter can only run a single thread at a time. Using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation. CPython 解释器一次只能运行一个线程。使用多个线程不会导致执行速度加快,除非至少有一个线程包含 I/O 操作。
from threading import Thread, Timer, RLock, Semaphore, Event, Barrier
from concurrent.futures import ThreadPoolExecutor, as_completed
Thread 线程
<Thread> = Thread(target=<function>) # Use `args=<collection>` to set the arguments.
<Thread>.start() # Starts the thread.
<bool> = <Thread>.is_alive() # Checks if the thread has finished executing.
<Thread>.join() # Waits for the thread to finish.
- Use
'kwargs=<dict>'to pass keyword arguments to the function. 使用'kwargs=<dict>'将关键字参数传递给函数。 - Use
'daemon=True', or the program will not be able to exit while the thread is alive. 使用'daemon=True',否则当线程处于活动状态时程序将无法退出。 - To delay thread execution use
'Timer(seconds, <func>)'instead of Thread(). 要延迟线程执行,请使用'Timer(seconds, <func>)'而不是 Thread()。
Lock 锁
<lock> = RLock() # Lock that can only be released by acquirer.
<lock>.acquire() # Waits for the lock to be available.
<lock>.release() # Makes the lock available again.
Or: 或者:
with <lock>: # Enters the block by calling acquire() and
... # exits it with release(), even on error.
Semaphore, Event, Barrier 信号量、事件、屏障
<Semaphore> = Semaphore(value=1) # Lock that can be acquired by 'value' threads.
<Event> = Event() # Method wait() blocks until set() is called.
<Barrier> = Barrier(n_times) # Wait() blocks until it's called n_times.
Queue 队列
<Queue> = queue.Queue(maxsize=0) # A thread-safe first-in-first-out queue.
<Queue>.put(<el>) # Blocks until queue stops being full.
<Queue>.put_nowait(<el>) # Raises queue.Full exception if full.
<el> = <Queue>.get() # Blocks until queue stops being empty.
<el> = <Queue>.get_nowait() # Raises queue.Empty exception if empty.
Thread Pool Executor 线程池执行器
<Exec> = ThreadPoolExecutor(max_workers=None) # Or: `with ThreadPoolExecutor() as <name>: ...`
<iter> = <Exec>.map(<func>, <args_1>, ...) # Multithreaded and non-lazy map(). Keeps order.
<Futr> = <Exec>.submit(<func>, <arg_1>, ...) # Creates a thread and returns its Future obj.
<Exec>.shutdown() # Blocks until all threads finish executing.
<bool> = <Future>.done() # Checks if the thread has finished executing.
<obj> = <Future>.result(timeout=None) # Waits for thread to finish and returns result.
<bool> = <Future>.cancel() # Cancels or returns False if running/finished.
<iter> = as_completed(<coll_of_Futures>) # Next() waits for next completed Future.
- Map() and as_completed() also accept 'timeout'. It causes futures.TimeoutError when next() is called. Map() times from original call and as_completed() from first call to next(). Map() 和 as_completed() 也接受“超时”。当 next() 被调用时,它会导致 futures.TimeoutError 。从原始调用开始的 Map() 时间和从第一次调用到 next() 的 as_completed() 时间。
- Exceptions that happen inside threads are raised when next() is called on map's iterator or when result() is called on a Future. Its exception() method returns exception or None. 当在 map 的迭代器上调用 next() 或在 Future 上调用 result() 时,会引发线程内部发生的异常。它的Exception()方法返回异常或None。
- ProcessPoolExecutor provides true parallelism, but everything sent to/from workers must be pickable. Queues must be sent using executor's 'initargs' and 'initializer' parameters. ProcessPoolExecutor 提供真正的并行性,但发送到/从工作线程发送的所有内容都必须是可选择的。必须使用执行器的“initargs”和“initializer”参数发送队列。
#Operator 运算符
Module of functions that provide the functionality of operators. Functions are ordered by operator precedence, starting with least binding. 提供运算符功能的功能模块。函数按运算符优先级排序,从最小绑定开始。
import operator as op
<bool> = op.not_(<obj>) # or, and, not (or/and missing)
<bool> = op.eq/ne/lt/le/gt/ge/contains/is_(<obj>, <obj>) # ==, !=, <, <=, >, >=, in, is
<obj> = op.or_/xor/and_(<int/set>, <int/set>) # |, ^, &
<int> = op.lshift/rshift(<int>, <int>) # <<, >>
<obj> = op.add/sub/mul/truediv/floordiv/mod(<obj>, <obj>) # +, -, *, /, //, %
<num> = op.neg/invert(<num>) # -, ~
<num> = op.pow(<num>, <num>) # **
<func> = op.itemgetter/attrgetter/methodcaller(<obj> [, ...]) # [index/key], .name, .name()
elementwise_sum = map(op.add, list_a, list_b)
sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
product_of_elems = functools.reduce(op.mul, <collection>)
first_element = op.methodcaller('pop', 0)(<list>)
- Bitwise operators require objects to have or(), xor(), and(), lshift(), rshift() and invert() special methods, unlike logical operators that work on all types of objects. 位运算符要求对象具有 or()、xor()、and()、lshift()、rshift() 和 invert() 特殊方法,这与适用于所有类型对象的逻辑运算符不同。
- Also:
'<bool> = <bool> &|^ <bool>'and'<int> = <bool> &|^ <int>'. 另外:'<bool> = <bool> &|^ <bool>'和'<int> = <bool> &|^ <int>'。
第二部分
Comprehensive Python Cheatsheet 综合 Python 备忘单P2 - 掘金 (juejin.cn)
March 17, 2024 2024 年 3 月 17 日Jure Šorn 尤雷·索恩 Chinese By Yulk yulike2017@outlook.com 2024 年 3 月 20 日