Python tips

12.28'23

pip list package and size

pip list|tail -n +3 | awk '{print $1}' | xargs pip show | grep -E 'Location:|Name:' | cut -d ' ' -f 2 | paste -d ' ' - - | awk '{print $2 "/" tolower($1)}' | xargs du -sh   2> /dev/null | sort -rh

PyPI Mirror

https://mirrors.sustech.edu.cn/help/pypi.html

pip install --upgrade pip --index-url https://mirrors.sustech.edu.cn/pypi/web/simple
pip config set global.index-url https://mirrors.sustech.edu.cn/pypi/web/simple

Jupyter

Getting started with JupyterLab(Python 3.5+)

pip install jupyterlab
jupyter lab

Plotly

pip install "ipywidgets>=7.5"
jupyter labextension install jupyterlab-plotly@4.8.1

Install pip

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

代码补全

  • Kite: 基于机器学习的代码补全工具
  • Python language server

Windows python 脚本获取不到参数(sys.argv)

需要修改注册表位置:

[HKEY_CLASSES_ROOT/Applications/python3.exe/shell/open/command]

值为

"C:\Program Files (x86)\python3\python3.exe" "%1" %*

zip 方法

zip(*iterables): 将多个可迭代对象聚合成一个迭代对象

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print(list(zipped))
# [(1, 4), (2, 5), (3, 6)]

柯里化

柯里化

在计算机科学中,柯里化(英语:Currying),又译为卡瑞化或加里化,是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术

对于

f(x, y)

如果存在

h = (x -> (y -> f(x, y)))

则柯里化是指

curry = (f -> h)

curry(f) = h

Lambda 函数

Lambda 函数是一个简短的匿名函数,可以接受任意个数的参数,但只能有一个表达式作为函数体。

Lambda 函数可以赋值给变量,也可以作为返回值。较普通函数使用更灵活。可以用于实现函数的柯里化。

x = lambda a : a + 10
print(x(5))

def myfunc(n):
    return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

取列表中某一段数据

arr[n:m]

获取 shell 命令输出

os.system 只会返回命令码(0 或其它)

os.popen 则可以获取命令输出结果

os.popen('cat /etc/services').read()

Python 打包

PyInstaller,支持多个平台将 Python 程序打包成独立的可执行文件。

下载 64 位 Python

Python Releases for Windows

Install whl 文件

pip install file.whl
📖