参考:https://blog.csdn.net/qq_40089648/article/details/89022804
quad
利用lambda定义匿名函数。
g = lambda a, b: a + b # 求 x+1 的和 print(g(1, 2)) # 上面函数等价于
输出结果为
3
上面函数等价为
def g(a, b):
return a+b
3.2 sorted
基本用法
参考: http://c.biancheng.net/view/2239.html
quad
sorted函数基本语法见下
list = sorted(iterable, key=None, reverse=False)
参数:其中iterable 表示指定的序列;key 参数可以自定义排序规则函数;reverse 参数为False为升序(默认),反之为降序。
返回值:返回一个排好序的列表,不影响原序列。
#对元组进行排序
a = (5,4,3,1,2)
# 返回为升序排列的列表,而非元组
print(sorted(a))
# 不改变原序列
print(a)
#字典默认按照key进行排序
a = {4:1, 5:2, 3:3, 2:6, 1:8}
print(sorted(a.items()))
#对字符串进行排序
a = "51423"
print(sorted(a))
输出结果为
[1, 2, 3, 4, 5] (5, 4, 3, 1, 2) [(1, 8), (2, 6), (3, 3), (4, 1), (5, 2)] ['1', '2', '3', '4', '5']利用key设置更多排序方式
传入key参数(函数),实现不同的排序方式,以匿名函数为例:
#利用key使得字典按照value进行排序
a = {4:1, 5:2, 3:3, 2:6, 1:8}
print(sorted(a.items(), key=lambda x : x[1]))
输出结果为
[(4, 1), (5, 2), (3, 3), (2, 6), (1, 8)]3.3 type,dtype,astype
参考:
https://blog.csdn.net/leilei7407/article/details/107672533
quad call函数使得类对象可以像函数一样调用
class A():
def __init__(self):
pass
def __call__(self, params):
print('you are using function call')
print('the params is ', params)
a = A()
a(10) # 类对象可以像函数一样调用
输出结果为
you are using function call the params is 10
quad 我们自己定义的神经网络常常会像下面这样使用,虽然class A中没有定义call函数,但是forward函数仍然被调用了,这是因为class A继承的nn.Module中定义了call函数,并且call函数调用了forward函数,class A覆盖了nn.Module的forward函数,则class A的forward函数就被调用了。
from torch import nn
class A(nn.Module):
def __init__(self):
super().__init__()
pass
def forward(self, params):
print('you are using function forward')
print('the params is ', params)
a = A()
a(10)
输出结果为
you are using function forward the params is 103.5 深复制与浅复制
quad
3.6 矩阵形状变换quad torch.view()与numpy.reshape()基本等价
import numpy as np import torch a = np.ones(shape=(2, 3)) print(a.reshape(-1, 6)) b = torch.ones(size=(2, 3)) print(b.view(-1, 6))
输出结果为:
[[1. 1. 1. 1. 1. 1.]] tensor([[1., 1., 1., 1., 1., 1.]])



