1. 转换Python list类型为numpy数组
先定义一个list列表,然后用np.ndarray
来转换
k = [[0,2,1],[0,1,0],[0,0,1]]
ret = np.asarray(k)
2. 变量相乘和矩阵相乘
#-*- coding:utf-8 -*-
import numpy as np
a = np.array([[1,1],
[0,1]])
b = np.arange(4).reshape(2,2) #b = [[0 1],
[2 3]]
c = a*b
c_dot = np.dot(a, b)
print(c)
print(c_dot)
变量相乘和矩阵相乘的输出结果如下
[[0 1]
[0 3]]
[[2 4]
[2 3]]
3. 求矩阵均值,两者相等
print(np.average(A))
print(np.mean(A))
np.median() #中位数
np.cumsum() #累加
np.diff() #累差
4.列表转换为字典的两个小方法
(1) 现在有两个列表,list1 = ['key1','key2','key3']
和list2 = ['1','2','3']
,把他们转为这样的字典:{'key1':'1','key2':'2','key3':'3'}
>>>list1 = ['key1','key2','key3']
>>>list2 = ['1','2','3']
>>>dict(zip(list1,list2))
{'key1':'1','key2':'2','key3':'3'}
(2) 将嵌套列表转为字典,有两种方法:
>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
>>>dict(list)
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
5. Python 字典排序(key、key_value)
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
sorted 语法及使用
sorted(iterable[, cmp[, key[, reverse]]])
conv_std_sort = sorted(conv_std.items(),key=lambda item:item[1],reverse=True) //对键值排序,reverse=True 倒序,False 顺序
conv_std_sort2 = sorted(conv_std)
6. numpy、PIL、tensor互相格式转换
PIL image 转 numpy格式
import numpy as np
res = np.asarray(img, np.uint8)
numpy 转 PILimage格式
from PIL import Image
img = Image.fromarray(img)
tensor 转 numpy
a = a.numpy()
a = a.cpu().detach().numpy() #在pytorch中,有时使用上一行代码将会报错,可能是这个变量中使用了如cuda之类的参数
numpy 转 tensor
import torch
torch.from_numpy(a)