Cham's Blog Algorithm, skill and thinking

Python 工程语法与代码简化

2020-10-22

Python 使用技巧记录,包括工程语法、代码简化等。

Cham’s Blog 首发原创

工程语法

数据文件索引

# 同一工程目录下
data = pd.read_csv('./data/train.csv')  # 或者 pd.read_csv('data/train.csv')

# 所在工程目录并列位置
data = pd.read_csv('../data/train.csv')

# 其他位置,使用绝对索引

定义和使用类

from torch import nn

# 定义
class MLP(nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(MLP, self).__init__()  # 子类继承父类的所有属性和方法
        self.hidden = nn.Linear(n_feature, n_hidden)
        self.act = nn.ReLU()
        self.out = nn.Linear(n_hidden, n_output)

    def forward(self, x):
        x = self.act(self.hidden(x))
        return self.out(x)

# 调用 (同一文件中,当此class不需要被其他文件调用时)
model = MLP(n_feature=2, n_hidden=4, n_output=2)
pred = model(X)

调用自定义函数

不管是自定义的 function 还是 class ,还是和 class 同一文件中的 function,按两种情况划分

1)如果自定义的文件和主文件在同一文件夹,在调用的同目录文件夹下新建名为 __init__.py 的文件

# 1. 导入全部/部分函数,函数前不需要指出是那个文件中的
from class_eg import *
from class_eg import MLP
mdl = MLP()
mdl.print()

from func_eg import *
from func_eg import print_date
print_date()

# 2. 导入文件,文件本身相当于一个类
import func_eg
func_eg.print_date()

2)如果自定义的文件和主文件在不同文件夹,使用绝对路径,比如 D:\Codes\PY\Trick,如果所有的文件夹都是在 PY 下边,只需要

from PY.Trick.func_eg import *
from PY.Trick.func_eg import print_date
print_date()

代码简化

if-else简化

x = 10 if (y == 9) else 20
x += 10 if (y == 9) else 20

if i in [1, 3, 5, 7]:
    pass

赋值简化

m, n = [1, 2]

特殊操作

# 1)找到列表中出现最频繁的数
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key=test.count))
# 4

# 2)从相关的序列构建字典
keys = (1, 2, 3)
values = (10, 20, 30)
print(dict(zip(keys, values)))
# -> {1: 10, 2: 20, 3: 30}

# 3)随机数产生
import numpy as np
np.random.randint(0, 10, size=(3,))  # 产生0~10之内的3个随机数
np.random.randint(0, 10, size=(3, 4))  # 产生0~10之内[3,4]矩阵大小的随机数

# 4)排列组合情况遍历
import itertools
direc_floor = list(itertools.product([0, 1], repeat=10))
# 10个元素,每个元素取0 or 1的所有可能组合

# 5)一行代码搜索字符串的多个前后缀
print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
# 1-> True
# 2-> True

list 和 ndarray 操作

# list
a = [10, 20, 30]
a.index(10)  # 查找第一个为10的元素的位置
a.count(10)  # 查找为10的元素的个数
[i for i in range(a) if a[i]==10]  # 查找所有为10元素位置
del a(i)  # 或 a.pop(i), a.remove(a[i]) 删除元素,注意删除顺序
[round(i, 2) for i in list_a]  # 保留小数点后两位

# ndarray
np.sum(ndarray == 1)  # 查询元素个数
np.where(ndarray == 1)  # 查询所有为1的元素位置

# 切片
# list索引只能用整数和切片,ndarray可以用list,tuple等索引,但是多维数组不能同时用list索引

# 删除数组某个元素
idx = list(range(9))
del idx[1]
idx = np.delete(np.arange(0, 9), 0)


Similar Posts

Comments