Python

资源

Google Colab
Kaggle Notebooks

语法

assert:

  • usage: assert expression [, arguments] = if not expression: raise AssertionError (arguments)
a = 1.5
assert 0 <= a <= 1, "a 不是概率的合理取值"

enumerate:

for i,x in enumerate(X):

type(var): 查看变量类型

help(func): 查看帮助

id(var) -> int: 查看变量内存地址

match:

match age:
	case x if x < 10:
		pass
	case 11 | 12:
		pass
	case _: # 其他
		pass

yield: 函数迭代器版 return

def foo():
    print("starting...")
    while True:
        res = yield 4
        print("res:",res)
        
g = foo() # 因为 foo 函数中有 yield 关键字,所以不会执行,而是先得到生成器 g
print(next(g)) # 运行到 yield 停止,不赋值,输出
print("*"*20)
print(next(g)) # 从上次停止的地方开始运行,赋值右边为 None(返回时没给左边传参数);输出下个循环遇到的 yeild

pickle - 读写变量到文件

var_file_path = 'var.pkl'
def save_var(data: dict):
    with open(var_file_path, 'wb') as file:
        pickle.dump(data, file)
def load_var() -> dict:
    with open(var_file_path, 'rb') as file:
        return pickle.load(file)

pymatgen - Python Materials Genomics

官网

pyperclip

复制文字到剪切板:

pyperclip.copy(text_to_copy)

tqdm - 进度条

from tqdm import tqdm

for item in tqdm(items):

typing

from typing import Literal

def fuc(a: Literal["a", "b"] = "a"): # 限制参数范围

traceback

try except 时输出错误信息

except:
    traceback.print_exc()

warnings

忽略警告:

warnings.filterwarnings('ignore', category=FutureWarning, module='sklearn')