python-cheatsheet

python-cheatsheet

Python编程指南与速查表 - 全面学习资源

python-cheatsheet项目是一个综合性的Python编程资源,包含详细的速查表和编程指南。它涵盖了从基础到高级的多个Python主题,如集合、数据类型、语法、系统操作、数据处理等。这个开源项目为开发者提供了便捷的参考工具,有助于提高编程效率和深入理解Python特性。

Python编程数据结构语法Github开源项目

Comprehensive Python Cheatsheet

<sup>Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. </sup>

Monty Python

Contents

    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__': # Skips next line if file was imported. main() # Runs `def main(): ...` function.

List

<el> = <list>[index] # First index is 0. Last -1. Allows assignments. <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.
  • Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
<int> = len(<list>) # Returns number of items. Also works on other collections. <int> = <list>.count(<el>) # Returns number of occurrences. Also `if <el> in <coll>: ...`. <int> = <list>.index(<el>) # Returns index of the first occurrence or raises ValueError. <el> = <list>.pop() # Removes and returns item from the end or at index if passed. <list>.insert(<int>, <el>) # Inserts item at index and moves the rest to the right. <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 >>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red']) >>> counter['yellow'] += 1 >>> print(counter) 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.

>>> from collections import namedtuple >>> Point = namedtuple('Point', 'x y') >>> p = Point(1, y=2); p 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(<coll>, start=0): # Returns next element and its index on each pass. ...

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.
  • 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> = 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:

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

>>> from collections.abc import Iterable, Collection, Sequence >>> isinstance([1, 2, 3], Iterable) True
+------------------+------------+------------+------------+ | | Iterable | Collection | Sequence | +------------------+------------+------------+------------+ | list, range, str | yes | yes | yes | | dict, set | yes | yes | | | iter | yes | | | +------------------+------------+------------+------------+
>>> from numbers import Number, Complex, Real, Rational, Integral >>> isinstance(123, Number) True
+--------------------+----------+----------+----------+----------+----------+ | | Number | Complex | Real | Rational | Integral | +--------------------+----------+----------+----------+----------+----------+ | int | yes | yes | yes | yes | yes | | fractions.Fraction | yes | yes | yes | yes | | | float | yes | yes | yes | | | | complex | yes | yes | | | | | decimal.Decimal | yes | | | | | +--------------------+----------+----------+----------+----------+----------+

String

Immutable sequence of characters.

<str> = <str>.strip() # Strips all whitespace characters from both ends. <str> = <str>.strip('<chars>') # Strips passed characters. Also lstrip/rstrip().
<list> = <str>.split() # Splits on one or more whitespace characters. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. <list> = <str>.splitlines(keepends=False) # 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>) # Returns start index of the first match or -1. <int> = <str>.index(<sub_str>) # Same, but raises ValueError if there's no match.
<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>) # Use `str.maketrans(<dict>)` to generate table.
<str> = chr(<int>) # Converts int to Unicode character. <int> = ord(<str>) # 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.
  • 'NFC' converts such characters to a single character, while 'NFD' converts them to two.

Property Methods

<bool> = <str>.isdecimal() # Checks for [0-9]. Also [०-९] and [٠-٩]. <bool> = <str>.isdigit() # Checks for [²³¹…] and isdecimal(). <bool> = <str>.isnumeric() # Checks for [¼½¾…],

编辑推荐精选

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多