大家好,我是云朵君,今天我又带来了干货,你准备好点赞了吗?
今天给大家带来一份由GitHub大神整理的一份python-cheatsheet
,整理地非常全面,有html及markdown两个版本,非常方便阅读和学习。
来源:github 链接:https://github.com/gto76/python-cheatsheet
索引页
这份索引页按照首字母顺序排列,可以看到共50页。建议下载后慢慢看。
内容总览
Collections
: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator. 列表,字典,集合,元组,范围,枚举,迭代器,生成器。Types
: Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime. 类型,字符串,正则表达式,格式,数字,组合,日期时间。Syntax
: Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception. 参数,内联,闭包,装饰器,类,Duck_Type,枚举,异常。System
: Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands. 退出,打印,输入,命令行参数,打开,路径,操作系统命令Data
: JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque.Advanced
: Threading, Operator, Introspection, Metaprograming, Eval, Coroutines. 线程,操作符,自省,元编程,Eval,协程。Libraries
: Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,NumPy, Image, Audio, Games, Data. 进度条,绘图,表,Curses,日志,抓取,网页,档案,NumPy,图像,音频,游戏,数据。
简单举例子
因为共有50页,不能一一例举,文末有获取方式!
Counter
代码语言:javascript复制>>> 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)
Regex
代码语言:javascript复制import re
<str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences with 'new'.
<list> = re.findall(<regex>, text) # Returns all occurrences as strings.
<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to include the matches.
<Match> = re.search(<regex>, text) # Searches for first occurrence of the pattern.
<Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
<iter> = re.finditer(<regex>, text) # Returns all occurrences as match objects.
- Search()和match()如果找不到匹配则返回None。
- 参数
'flags=re.IGNORECASE'
可用于所有函数。 - 参数
'flags=re.MULTILINE'
使'^'
和'$'
匹配每行的开始/结束。 - 参数
'flags=re.DOTALL'
使点也接受'n'
。 - 使用
r'1'
或'\1'
作为反向引用。 - 不贪心正则是在操作符后添加
'?'
。
Arguments
Inside Function Call
代码语言:javascript复制<function>(<positional_args>) # f(0, 0)
<function>(<keyword_args>) # f(x=0, y=0)
<function>(<positional_args>, <keyword_args>) # f(0, y=0)
Inside Function Definition
代码语言:javascript复制def f(<nondefault_args>): # def f(x, y):
def f(<default_args>): # def f(x=0, y=0):
def f(<nondefault_args>, <default_args>): # def f(x, y=0):
Splat Operator
Inside Function Call
Splat将集合扩展为位置参数,而splty - Splat则将字典扩展为关键字参数。
代码语言:javascript复制args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs)
Is the same as:
代码语言:javascript复制func(1, 2, x=3, y=4, z=5)
Inside Function Definition
Splat将零个或多个位置参数组合成一个元组,而splty - Splat将零个或多个关键字参数组合成一个字典。
代码语言:javascript复制def add(*a):
return sum(a)
代码语言:javascript复制>>> add(1, 2, 3)
6
Legal argument combinations:
代码语言:javascript复制def f(x, y, z): # 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, 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)
代码语言:javascript复制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(x, *args, z): # f(1, 2, z=3)
代码语言:javascript复制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(*, x, **kwargs): # f(x=1, y=2, z=3)
代码语言:javascript复制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, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
Other Uses
代码语言:javascript复制<list> = [*<collection> [, ...]]
<set> = {*<collection> [, ...]}
<tup.> = (*<collection>, [...])
<dict> = {**<dict> [, ...]}
代码语言:javascript复制head, *body, tail = <collection>
Open
打开文件并返回相应的文件对象。
代码语言:javascript复制<file> = open(<path>, mode='r', encoding=None, newline=None)
'encoding=None'
表示使用默认编码,这是依赖于平台的。最佳实践是尽可能使用'encoding="utf-8"'
。'newline=None'
表示读取时将所有不同的行组合结束符转换为'n',而写入时将所有'n'字符转换为系统默认的行分隔符。'newline=""'
表示没有发生转换,但readline()和readlines()仍然会在'n', 'r' 或 'rn'上将输入分割成块。
Modes
'r'
- Read (default).'w'
- Write (truncate).'x'
- Write or fail if the file already exists.'a'
- Append.'w '
- Read and write (truncate).'r '
- Read and write from the start.'a '
- Read and write from the end.'t'
- Text mode (default).'b'
- Binary mode.
Exceptions
'FileNotFoundError'
可以在读取'r'或'r '时引发。 .'FileExistsError'
可以在写'x'
时被引发。'IsADirectoryError'
和'PermissionError'
可以是任何错误.'OSError'
是所有列出的异常的父类。
File Object
代码语言:javascript复制<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.
代码语言:javascript复制<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.
代码语言:javascript复制<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.
方法不会添加或去掉末尾的换行符,即使是writelines()。
Read Text from File
代码语言:javascript复制def read_file(filename):
with open(filename, encoding='utf-8') as file:
return file.readlines()
Write Text to File
代码语言:javascript复制def write_to_file(filename, text):
with open(filename, 'w', encoding='utf-8') as file:
file.write(text)
SQLite
无服务器数据库引擎,将每个数据库存储到单独的文件中。
Connect
打开到数据库文件的连接。如果path不存在,则创建一个新文件。
代码语言:javascript复制import sqlite3
<conn> = sqlite3.connect(<path>) # Also ':memory:'.
<conn>.close() # Closes the connection.
Read
返回值可以是str、int、float、bytes或None类型。
代码语言:javascript复制<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
代码语言:javascript复制<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:
代码语言:javascript复制with <conn>: # Exits the block with commit() or rollback(),
<conn>.execute('<query>') # depending on whether an exception occurred.
Placeholders
传递的值可以是str, int, float, bytes, None, bool, datetime类型。日期或datetime.datetme。boolean将以ISO格式化字符串的整数和日期形式存储和返回。
代码语言:javascript复制<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.
Example
在这个例子中,值实际上没有保存,因为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)]
MySQL
有一个非常相似的界面,有以下列出的差异.
代码语言:javascript复制# $ pip3 install mysql-connector
from mysql import connector
<conn> = connector.connect(host=<str>, …) # `user=<str>, password=<str>, database=<str>`.
<cursor> = <conn>.cursor() # Only cursor has execute method.
<cursor>.execute('<query>') # Can raise a subclass of connector.Error.
<cursor>.execute('<query>', <list/tuple>) # Replaces '%s's in query with values.
<cursor>.execute('<query>', <dict/namedtuple>) # Replaces '%(<key>)s's with values.