Python教程备忘录


这是一个非常全面的 Python 备忘单,适合任何感兴趣的人。它绝对是可用的最详细的之一。点击标题


列表

<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
<list>.append(<el>)             # Or: <list> += [<el>]
<list>.extend(<collection>)     # Or: <list> += <collection>
<list>.sort()                  # 按升序排序。
<list>.reverse()                # 就地反转列表。
<list> = sorted(<collection>)  # 返回新的排序列表。
<iter> = reversed(<list>)       # 返回反向迭代器。


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

有关 Sorted()、min() 和 max() 的详细信息,请参阅sortable
模块运算符提供了函数 itemgetter() 和 mul(),它们提供与上面的[url=https://github.com/gto76/python-cheatsheetlambda]lambda[/url]表达式相同的功能。

<list>.insert(<int>, <el>)      # 插入索引处的项目,并将其余项目向右移动。
<el>  = <list>.pop([<int>])     # 删除并返回索引处或末尾的项目。
<int> = <list>.count(<el>)      # 返回出现次数。也适用于字符串。
<int> = <list>.index(<el>)      # 返回第一次出现的索引或引发 ValueError。
<list>.remove(<el>)            # 删除第一个出现的项目或引发 ValueError。
<list>.clear()                  # 删除所有项目。也适用于字典和套装。

字典

<view> = <dict>.keys()                         # 反映变化的按键总数。
<view> = <dict>.values()                        # 反映变化的数值。
<view> = <dict>.items()                         # 反映 chgs 的键值图元的总数。

value  = <dict>.get(key, default=None)          # 如果键丢失,则返回默认值。
value  = <dict>.setdefault(key, default=None)  # 如果键丢失,则返回并写入默认值。
<dict> = collections.defaultdict(<type>)        # 返回具有默认值 `<type>()`的 dict。
<dict> = collections.defaultdict(lambda: 1)     # 返回一个默认值为 1 的 dict。

<dict> = dict(<collection>)                    # 根据键值对创建 dict。
<dict> = dict(zip(keys, values))                # 从两个集合创建一个 dict。
<dict> = dict.fromkeys(keys [, value])          # 从键集合中创建一个 dict。

<dict>.update(<dict>)                           # 添加项目。用匹配的密钥替换物品。
value = <dict>.pop(key)                        # 删除项目,如果缺少则引发 KeyError。
{k for k, v in <dict>.items() if v == value}    # 返回指向值的键集。
{k: v for k, v in <dict>.items() if k in keys}  按键筛选后返回字典

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()                              # 如果为空,则引发 KeyError。
<set>.remove(<el>)                              # 如果缺少,则引发 KeyError。
<set>.discard(<el>)                             # 不会引发错误。

Tuple
Tuple 是不可变且可散列的列表。

<tuple> = ()                               # Empty tuple.
<tuple> = (<el>,)                          # Or: <el>,
<tuple> = (<el_1>, <el_2> [, ...])         # Or: <el_1>, <el_2> [, ...]

Type类型

  • 一切都是对象。
  • 每个对象都有一个类型。
  • 类型和类是同义词。

<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'>)


有些类型没有内置名称,因此必须导入:
from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleType

String字符
不可变字符集

<str>  = <str>.strip()                       # 删除两端的所有空白字符。
<str>  = <str>.strip('<chars>')             # 剪切传递的字符。也是 lstrip/rstrip()。

<list> = <str>.split()                      # 分割一个或多个空白字符。
<list> = <str>.split(sep=None, maxsplit=-1)  # 在'sep'字符串上最多分割'maxsplit'次。
<list> = <str>.splitlines(keepends=False)    # On [\n\rf\x1c-\x1e\x85\u2028\u2029] and\r\n.
<str>  = <str>.join(<coll_of_strings>)       # 使用字符串作为分隔符连接元素。

<bool> = <sub_str> in <str>                  # 检查字符串是否包含子串。
<bool> = <str>.startswith(<sub_str>)         # 为多个选项传递字符串元组。
<bool> = <str>.endswith(<sub_str>)           # Pass tuple of strings for multiple options.
<int>  = <str>.find(<sub_str>)              # 返回第一个匹配项的起始索引或 -1。
<int>  = <str>.index(<sub_str>)             # 相同,但如果缺少会引发 ValueError。

<str>  = <str>.lower()                       # 更改大小写。同样使用 upper/capitalize/title()。
<str>  = <str>.replace(old, new [, count])   # 用 "新 "替换 "旧 "的次数最多为 "count"
<str>  = <str>.translate(<table>)            # 使用 `str.maketrans(<dict>)` 生成表格。

<str>  = chr(<int>)                          # 将 int 转换为 Unicode 字符。
<int>  = ord(<str>)                          # 将 Unicode 字符转换为 int

正则
正则表达式匹配函数

import re

<str>   = re.sub(<regex>, new, text, count=0)  # 用 "新 "代替所有出现的内容。
<list>  = re.findall(<regex>, text)            # 返回所有出现的字符串。
<list>  = re.split(<regex>, text, maxsplit=0)  # 在 regex 前添加括号,以包含匹配项。
<Match> = re.search(<regex>, text)             # 首次出现或无。
<Match> = re.match(<regex>, text)              # 仅搜索文本开头。
<iter>  = re.finditer(<regex>, text)          # 返回所有出现的匹配对象。

  • 参数 "new "可以是一个接受 Match 对象并返回字符串的函数。
  • 参数 "flags=re.IGNORECASE "可用于所有函数。
  • 参数'flags=re.MULTILINE'会使'^'和'$'匹配每一行的起始/结束位置。
  • 参数'flags=re.DOTALL'使'.'也接受'\n'。
  • 使用 r'\1' 或 '\1' 进行反向引用('\1' 返回八进制代码为 1 的字符)。
  • 在'*'和'+'后面添加'?

格式:

<str> = f'{<el_1>}, {<el_2>}'            大括号也可以包含表达式
<str> = '{}, {}'.format(<el_1>, <el_2>)  # 或: '{0}, {a}'.format(<el_1>, a=<el_2>)
<str> = '%s, %s' % (<el_1>, <el_2>)      # 冗余、低劣的 C 风格格式。

>>> 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.'


字符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%'

整数

{90:c}                                   # 'Z'
{90:b}                                   # '1011010'
{90:X}                                   # '5A'


<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>)'和'float(<str>)'会对畸形字符串引发 ValueError。
  • 十进制数是精确存储的,不像大多数浮点数那样 "1.1 + 2.2 != 3.3"。
  • 浮点数可以用math.isclose(<float>,<float>)"。
  • 十进制运算的精度可以用'decimal.getcontext().prec = <int>'。

组合

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 "和 "timedelta "类。所有类都不可变且可散列。

# pip3 install python-dateutil
from datetime import date, time, datetime, timedelta, timezone
from dateutil.tz import tzlocal, gettz

<D>  = date(year, month, day)              # 只接受公元 1 至 9999 年的有效日期。
<T>  = time(hour=0, minute=0, second=0)     # 另外:`microsecond=0, tzinfo=None, fold=0`。
<DT> = datetime(year, month, day, hour=0)   # 还有:"分钟=0,秒=0,微秒=0,......"
<TD> = timedelta(weeks=0, days=0, hours=0)  # Also: `minutes=0, seconds=0, microseconds=0`.

  • Aware <a> 时间和日期时间对象有定义的时区,而 naive <n> 没有。如果对象是幼稚的,则假定它处于系统时区!
  • fold=1 "表示在时间向后跳转一小时的情况下进行第二次跳转。
  • Timedelta 会将参数标准化为±日、秒(< 86 400)和微秒(< 1M)。
  • 使用"<D/DT>.weekday() "以 int 表示星期几,星期一为 0。

<D/DTn>  = D/DT.today()                     # 当前本地日期或天真 DT。也是 DT.now()。
<DTa>    = DT.now(<tzinfo>)                 # 从通过的时区的当前时间开始认识 DT。

<tzinfo> = timezone.utc                     # 伦敦不设夏令时(DST)。
<tzinfo> = timezone(<timedelta>)             UTC 有固定偏移的时区。
<tzinfo> = tzlocal()                        具有动态偏移的本地 tz。也可使用 gettz()。
<tzinfo> = gettz('<Continent>/<City>')      /城市名 "时区或无。
<DTa>    = <DT>.astimezone([<tzinfo>])       DT 转换为已通过或本地的固定区域。
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>)  # 无需转换即可更改对象的时区。

  • 由 gettz()、tzlocal() 和 naive 对象的隐式本地时区返回的时区,其偏移量会因 DST 和时区基准偏移量的历史变化而随时间变化。
  • 在 Python 3.9 及更高版本中,可以使用标准库的 zoneinfo.ZoneInfo() 代替 gettz()。在 Windows 上,它需要 "tzdata "软件包。如果省略 arg.,则不会返回本地 tz。

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__

  • repr() 的返回值应明确无误,str() 的返回值也应可读。
  • 如果只定义了 repr(),它也将用于 str()。
  • 使用"@staticmethod "装饰的方法不会将 "self "或 "cls "作为第一个参数。

更多完整列表备忘录点击标题