python
本文最后更新于 2025年11月9日 下午
引用
module
package:有”.口”
绝对
相对
需要导入相关package
安装换源
-i https://pypi.douban.com/simple
解包
元素列,没有外面的括号
*args 列表、键,**kwargs键值对,作为函数参数先后
类型制定
def func(a: type_a =init) -> type_b
A|B
typing.Callable[[input],output ]
list[]
异步
async/await
与[[JavaScript#typescript]]比异步函数不能直接创造线程,需要用asyncio管理task
迭代器
迭代器是实现了
__next__()方法的对象,用于逐个返回元素。可迭代对象是实现
__iter__()的对象(如列表、元组、字典等),可以被转换为迭代器。生成器表达式:(f(x) for x in seq) 惰性产生元素,适合大数据串流处理。
enumerate 返回的是一个迭代器(可一次性向前消费)。对于很大的数据,使用 enumerate 比 range(len(seq)) 更省内存、更 Pythonic。
itertools.count() 类似于自然数迭代器
生成器:迭代器的一种写法
1 | |
魔法方法
~Haskell类
A[slice]对应__getitem__ 其中 start:stop:step 是slice(start, stop, step) 的缩写, 习惯上左闭右开
可以用silce.start … 访问
实际上还可以是一个元组
1 | |
venv
python -m venv /path/to/new/virtual/environment
.venv\Scripts\activate
[[NumPy]]
Pandas
[[Matplotlib]]
[[Jupyter]]
[[Pytorch]]
[[Manim_learn]]
Networkx
1 | |
The Zen of Python @Tim Peters
美丽总比丑陋好。
Beautiful is better than ugly.
显式比隐式好。
Explicit is better than implicit.
简单胜于复杂。
Simple is better than complex.
复杂比复杂好。
Complex is better than complicated.
扁平比嵌套好。
Flat is better than nested.
稀疏比密集好。
Sparse is better than dense.
可读性。
Readability counts.
特殊情况并不特别到可以打破规则。
Special cases aren’t special enough to break the rules.
尽管实用性胜过纯洁性。
Although practicality beats purity.
错误绝不能悄无声息地过去。
Errors should never pass silently.
除非明确沉默。
Unless explicitly silenced.
面对模棱两可,拒绝猜测的诱惑。
In the face of ambiguity, refuse the temptation to guess.
应该有一种——最好只有一种——明显的方法来做到这一点。
There should be one– and preferably only one –obvious way to do it.
虽然这种方式一开始并不明显,除非你是荷兰人。
Although that way may not be obvious at first unless you’re Dutch.
现在总比没有好。
Now is better than never.
虽然永远都比现在好。
Although never is often better than right now.
如果实现很难解释,那它就是一个坏主意。
If the implementation is hard to explain, it’s a bad idea.
如果实现很容易解释,它可能是一个好主意。
If the implementation is easy to explain, it may be a good idea.
名称空间是一个非常棒的想法——让我们做更多这样的事情! Namespaces are one honking great idea – let’s do more of those!
misc
“海象运算符”(Walrus Operator),它使用 := 符号, 赋值并返回值