Python 进阶学习

1、VsCode Debug 配置文件

  • 配置当前路径、命令行参数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    "configurations": [
    {
    "name": "Python: 当前文件",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "args": [
    "--data", "./data/",
    "--output", "./output/",
    "--lang", "en"],
    "cwd": "${fileDirname}"
    }
    ]

2、生成requirements.txt

1
2
python -m pip install pipreqs
pipreqs ./ --encoding=utf-8

3、单星号、双星号

  • 单星号(*):*agrs,将所以参数以元组(tuple)的形式导入
  • 双星号(**):**kwargs,将参数以字典的形式导入
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    def foo(param1, *param2):
    print(param1)
    print(param2)
    print(param2[2])
    foo(1, 2, 3, 4, 5)

    def bar(param1, **param2):
    print(param1)
    print(param2)
    print(param2["a"])
    bar(1, a=2, b=3)

    """
    输出:
    1
    (2, 3, 4, 5)
    4
    1
    {'a': 2, 'b': 3}
    2
    """

4、list, np.array, torch.tensor 相互转换

1
2
3
4
5
6
7
8
ndarray = np.array(list)  # list 转 numpy数组
list = ndarray.tolist() # numpy 转 list

tensor=torch.Tensor(list) # list 转 torch.Tensor
list = tensor.numpy().tolist() # torch.Tensor 转 list 先转numpy,后转list

ndarray = tensor.cpu().numpy() # torch.Tensor 转 numpy *gpu上的tensor不能直接转为numpy
tensor = torch.from_numpy(ndarray) # numpy 转 torch.Tensor

5、np.array, torch.tensor 数组嵌套

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np
a = [1, 2, 3]
b = [0, 1, 0]
a = np.array(a)
b = np.array(b)
c = a[b]
print(c)
# 输出:[1 2 1]


import torch
a = [1, 2, 3]
b = [0, 1, 0]
a = torch.Tensor(a)
b = torch.Tensor(b)
b = b.gt(0)
c = a[b]
print(c)
# 输出:tensor([2.])

6、Python 执行 shell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os
import subprocess

x1 = os.system('pwd') # 直接输出shell结果,不会赋值给x1
print('x1', x1) # 打印结果:0, 表示命令执行成功

x2 = os.popen('pwd').read() # 不直接输出shell结果,会赋值给x2
print('x2', x2) # 打印结果:/home/zzk, os.popen() 返回的是一个【文件对象】

x3 = subprocess.call('pwd', shell=True) # 直接输出shell结果
print('x3', x3) # 打印结果:0

subprocess.call('echo 123', shell=True)
subprocess.call(['echo', '456'], shell=False)
x4 = subprocess.Popen('cd ../ && pwd', stdout=subprocess.PIPE, shell=True)
print('x4', x4.communicate()) # 打印结果

7、卸载所有三方包

1
2
3
pip list
pip freeze>python_modules.txt
pip uninstall -r python_modules.txt -y
坚持原创技术分享,您的支持将鼓励我继续创作!
0%