Python: 数据类型转换总结
总结记录在深度学习中经常用到的list,np,array,和torch.tensor数据类型的转换过程。
1.list,np.array和torch.tensor数据类型转换
- 定义三种类型变量
- 简单list类型:
l = [1, 2, 3, 4, 5] - np.array类型:
a = np.array([1, 2, 3, 4, 5]) - torch.tensor类型:
t = torch.tensor([1, 2, 3, 4, 5])
1.1 list与np.array之间转换
1.1.1 listtonp.array
l2a = np.array(l)
1.1.2 np.arraytolist
a2l = a.tolist()
1.2 list与torch.tensor之间转换
1.2.1 listtotorch.tensor
l2t = torch.tensor(l)
1.2.2 torch.tensortolist
t2l = t.tolist()
1.3 np.array与torch.tensor之间转换
1.3.1 np.arraytotorch.tensor
a2t = torch.from_numpy(a)
1.3.2 torch.tensortonp.array之间转换
t2a = t.numpy()
1.4. list[torch.tensor]tolist之间转换
d = [torch.tensor(1), torch.tensor(2), torch.tensor(3), torch.tensor(4)]
d2l = [tensor.tolist() for tensor in d]