¶ 语法
缩进应该使用4个空格而不是tab:https://peps.python.org/pep-0008/#tabs-or-spaces
¶ for循环
0到9循环:
for i in range(10) : |
在交互式环境中(如命令行形式)后面要多打一个回车才开始运行
¶ 内置数据结构
¶ List
a = [1, 2, 3, 4] |
truncate:
del l[100:] |
来源:https://stackoverflow.com/questions/4838504/how-do-i-truncate-a-list
¶ 字典
Python教学: Python Dictionary完全教学一次搞懂
¶ 遍历
likes = {"color": "blue", "fruit": "apple", "pet": "dog"} |
输出:
color |
for (key, value) in likes.items(): |
输出:
color blue |
来源:https://realpython.com/iterate-through-dictionary-python/
¶ 其他
¶ 类
from dataclasses import dataclass |
参考:https://stackoverflow.com/questions/35988/c-like-structures-in-python
完整教程:Python 面向对象
¶ 输入
¶ 输出
¶ 输出为科学计数法
参考:https://blog.csdn.net/qq_45434742/article/details/102094577?fps=1&locationNum=2
print("%e" %111) |
¶ 不打印换行符
print('hello', end='') |
¶ 打印到stderr
print('xxx', file=sys.stderr) |
来源:https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python
¶ 指定分隔符打印数组
1, 2, 3, 4, 5] L = [ |
来源:https://stackoverflow.com/questions/22556449/print-a-list-of-space-separated-elements
¶ format
打印到字符串。完整教程:https://note.nkmk.me/en/python-format-zero-hex/
这里介绍一些常用的。
保留3位小数:assert '{:.3f}'.format(2.3) == '2.300'
¶ iterator
遍历:
it = iter([1, 2, 3]) |
for
循环会自动catch StopIteration
:
it = iter([1, 2, 3]) |
¶ 文件
python文件管理¶ 切换到脚本所在目录
import sys |
¶ 打印到文件
使用print
的file
参数:
f = open(路径, 'w') |
来源:https://www.askpython.com/python/built-in-methods/python-print-to-file
¶ Exceptions
Built-in Exceptions: https://docs.python.org/3/library/exceptions.html
常用的:
¶ 标准库
¶ bisect 二分
¶
bisect_left
类似于C++的std::lower_bound
,找第一个大于等于的。
bisect.bisect_left(a, x, lo=0, hi=len(a), *, key=None) |
¶
坑点:pandas.Series
不能用bisect
pandas.Series
重载了[]
运算符,所以不能用bisect
二分:https://stackoverflow.com/questions/73757757/python-bisect-and-pandas-dataframe-keyerror
需要用它自带的searchsorted二分:
x = pd.Series([1, 2, 3]) |
3 |
¶ io
https://stackoverflow.com/questions/39823303/python3-print-to-string
¶ 时间
https://docs.python.org/3/library/datetime.html
datetime.datetime.fromtimestamp(1516332287) |
也可以用time
包:Python中时间与时间戳之间的转换
¶ math
¶ 阶乘
10!
from math import * |
¶ 正则
https://docs.python.org/3/library/re.html
¶ 执行命令
¶ 简单执行命令
os.system('命令 参数...') |
返回值是OS-dependant:https://stackoverflow.com/questions/6466711/what-is-the-return-value-of-os-system-in-python
可以用os.waitstatus_to_exitcode来将返回值变成exit code。如果正常退出,exit code就是0。
¶ 带参数命令
import subprocess |
文档:https://docs.python.org/3/library/subprocess.html#subprocess.run
¶ 可kill的命令
用subprocess.Popen
: https://stackoverflow.com/questions/43322201/how-to-kill-process-which-created-by-python-os-system
文档:https://docs.python.org/3/library/subprocess.html#popen-constructor
¶ 获取命令输出
¶ 排序
用sorted
。
¶ 对字典的key排序
x = {1: 2, 4: 3, 2: 1} |
[1, 2, 4] |
¶ 对字典的值排序
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} |
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)] |
来源:https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value
¶ shlex
可以用解析命令行参数的方式解析字符串。文档:https://docs.python.org/3/library/shlex.html
例子:
# https://stackoverflow.com/a/899314 |
['-o', '1', '--long', 'Some long string'] |
¶ argparse
基础用法:
import argparse |
¶ getopt
用法跟C语言的getopt
差不多。
¶ 取整
四舍五入:round
向上取整:math.ceil
向下取整:math.floor
¶ 其他
Waiting for I/O completion: https://docs.python.org/3/library/select.html
字符串trim: https://www.freecodecamp.org/news/python-strip-how-to-trim-a-string-or-line/
¶ 三方库
¶ dateutil
https://dateutil.readthedocs.io/en/stable/
pip3 install python-dateutil |
可以实现时间减去月数等功能。
来源:https://thispointer.com/subtract-months-from-a-date-in-python/
¶ pandas
官方文档:https://pandas.pydata.org/docs/
pandas数据框常用操作¶ Serias
官方文档:https://pandas.pydata.org/docs/reference/api/pandas.Series.html
常用成员函数
取平均:https://pandas.pydata.org/docs/reference/api/pandas.Series.mean.html
¶ numpy
numpy学习笔记¶ json
¶ 字典和json字符串的转换
import json |
¶ 从文件读取
import json |
但是遇到trailing comma会报错。可以用json5: https://stackoverflow.com/questions/23705304/can-json-loads-ignore-trailing-commas
pip3 install json5 |
import json5 |
¶ func_timeout
https://github.com/kata198/func_timeout
func_timeout
的原理是开一个新的线程执行函数,timeout之后会raise
exception,然后开一个新线程来join,所以timeout之后子线程可能会继续输出:
from func_timeout import func_timeout, FunctionTimedOut |
输出:
test |
如果需要等待join完成,需要使用StoppableThread
:https://htmlpreview.github.io/?https://raw.githubusercontent.com/kata198/func_timeout/master/doc/func_timeout.StoppableThread.html
from func_timeout import FunctionTimedOut |
输出:
test |
¶ pip
安装指定版本:https://www.marsja.se/pip-install-specific-version-of-python-package/
requirements.txt: https://note.nkmk.me/en/python-pip-install-requirements/
¶ 有关
¶ 已知的问题
调用另一个文件里的函数不太方便: https://www.geeksforgeeks.org/python-import-module-from-different-directory/