¶ 语法
缩进应该使用4个空格而不是tab:https://peps.python.org/pep-0008/#tabs-or-spaces
¶ for循环
0到9循环:
for i in range(10) :
Statements
在交互式环境中(如命令行形式)后面要多打一个回车才开始运行
¶ 内置数据结构
¶ List
= [1, 2, 3, 4]
a
# 最后一个元素
# 4
-1]
a[
# 从index为1的元素开始的所有元素
# [2, 3, 4]
1:]
a[
# 以最后一个元素结尾(不含)的所有元素
# [1, 2, 3]
-1]
a[:
# 以倒数第二个元素结尾(不含)的所有元素
# [1, 2]
-2] a[:
truncate:
del l[100:]
来源:https://stackoverflow.com/questions/4838504/how-do-i-truncate-a-list
¶ 字典
Python教学: Python Dictionary完全教学一次搞懂
¶ 遍历
= {"color": "blue", "fruit": "apple", "pet": "dog"}
likes for key in likes:
print(key)
输出:
color
fruit
pet
for (key, value) in likes.items():
print(key, value)
输出:
color blue
fruit apple
pet dog
来源:https://realpython.com/iterate-through-dictionary-python/
¶ 其他
¶ 类
from dataclasses import dataclass
@dataclass
class A:
int
a: str
b: float
c: list[A] = []
li: 1, "2", 3.3))
li.append(A(2, "3", 4.4))
li.append(A(print(li)
# [<class '__main__.A'>, A(a=1, b='2', c=3.3), A(a=2, b='3', c=4.4)]
= li[1]
item print(item.c)
# 3.3
sorted(li, key = lambda item: item.c, reverse=True)
参考: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)
= 111
x print("%e" %x)
print("%e" %(111 + 111))
print("%e %e" %(x, 111 + 111))
¶ 不打印换行符
print('hello', end='')
¶ 打印到stderr
print('xxx', file=sys.stderr)
来源:https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python
¶ 指定分隔符打印数组
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
来源: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
遍历:
= iter([1, 2, 3])
it while True:
try:
print(next(it))
except StopIteration:
break
for
循环会自动catch StopIteration
:
= iter([1, 2, 3])
it for x in it:
print(x)
¶ 文件
python文件管理¶ 切换到脚本所在目录
import sys
import os
= os.path.abspath(sys.argv[0])
abspath = os.path.dirname(abspath)
dname os.chdir(dname)
¶ 打印到文件
使用print
的file
参数:
= open(路径, 'w')
f print('Average %f' %average, file=f)
来源: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
,找第一个大于等于的。
=0, hi=len(a), *, key=None) bisect.bisect_left(a, x, lo
¶
坑点:pandas.Series
不能用bisect
pandas.Series
重载了[]
运算符,所以不能用bisect
二分:https://stackoverflow.com/questions/73757757/python-bisect-and-pandas-dataframe-keyerror
需要用它自带的searchsorted二分:
= pd.Series([1, 2, 3])
x 4) x.searchsorted(
3
¶ io
https://stackoverflow.com/questions/39823303/python3-print-to-string
¶ 时间
https://docs.python.org/3/library/datetime.html
1516332287) datetime.datetime.fromtimestamp(
也可以用time
包:Python中时间与时间戳之间的转换
¶ math
¶ 阶乘
10!
from math import *
10) factorial(
¶ 正则
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
'./executable', arg1, arg2]) subprocess.run([
文档: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排序
= {1: 2, 4: 3, 2: 1}
x sorted(x)
[1, 2, 4]
¶ 对字典的值排序
= {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
x sorted(x.items(), key=lambda item: item[1])
[(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
import shlex
'-o 1 --long "Some long string"') shlex.split(
['-o', '1', '--long', 'Some long string']
¶ 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
# 使用tab进行缩进。
='\t') json.dumps(obj, indent
¶ 从文件读取
import json
open(路径)) json.load(
但是遇到trailing comma会报错。可以用json5: https://stackoverflow.com/questions/23705304/can-json-loads-ignore-trailing-commas
pip3 install json5
import json5
open(路径)) json5.load(
¶ func_timeout
https://github.com/kata198/func_timeout
func_timeout
的原理是开一个新的线程执行函数,timeout之后会raise
exception,然后开一个新线程来join,所以timeout之后子线程可能会继续输出:
from func_timeout import func_timeout, FunctionTimedOut
import os
def test():
for _ in range(0, 2):
'for i in $(seq 1 2); do sleep 1; echo test; done')
os.system(
try:
1.5, test)
func_timeout(except FunctionTimedOut:
print('Timeout')
except Exception as e:
# Code to handle any other exception
print("An error occurred: {}".format(str(e)))
输出:
test
Timeout
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
from func_timeout.StoppableThread import StoppableThread
import subprocess
def test():
try:
for _ in range(0, 2):
= subprocess.Popen(['bash', '-c', 'for i in $(seq 1 2); do sleep 1; echo test; done'])
process # We must wait with timeout, otherwise it won't respond to external exceptions.
# https://stackoverflow.com/a/631605/13688160
=23333333)
process.wait(timeoutexcept FunctionTimedOut:
try:
# It seems to be okay even if process.wait is completed
process.kill()except NameError:
pass
def test_timeout(seconds):
= StoppableThread(target=test)
worker
worker.start()=seconds)
worker.join(timeoutif worker.is_alive():
print('Timeout')
=FunctionTimedOut)
worker.stop(exception
worker.join()print('Joined')
1.5)
test_timeout(4.5) test_timeout(
输出:
test
Timeout
Joined
test
test
test
test
Joined
¶ 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/