python 中 list,numpy,tensor的互相转换

import torch
import numpy as np


print('##########建立 a-list;; b-numpy;; c- tensor##########')
a = [1,2,3,4,5]
b = np.array([1,2,3,4,5])
c = torch.arange(1,6)
print('a-list:',a,'\n',
      'b-ndarray:',b,'\n',
      'c-tensor:',c,c.type())

print('\n########list转numpy  和  tensor  ###############')
list_numpy = np.array(a)
list_tensor = torch.tensor(a)
print(list_numpy,list_tensor)

print('\n##########numpy转 list  和  tensor  ##########')
numpy_list = b.tolist()
numpy_tensor = torch.from_numpy(b)
print(numpy_list,numpy_tensor)

print('\n##############tensor 转 list (先转numpy,后转list)  和  numpy  ##########')
tensor_list = c.numpy().tolist()
tensor_numpy = c.numpy()
print(tensor_list,tensor_numpy)

# 如果tensor是GPU上的tensor,先转成CPU,再转为numpy
ndarray = tensor.cpu().numpy()

#输出#

E:\Anconda\python.exe "C:/Users/MR-LI/Desktop/program practice/TRY/train.py"
##########建立 a-list;; b-numpy;; c- tensor##########
a-list: [1, 2, 3, 4, 5] 
 b-ndarray: [1 2 3 4 5] 
 c-tensor: tensor([1, 2, 3, 4, 5]) torch.LongTensor

########list转numpy  和  tensor  ###############
[1 2 3 4 5] tensor([1, 2, 3, 4, 5])

##########numpy转 list  和  tensor  ##########
[1, 2, 3, 4, 5] tensor([1, 2, 3, 4, 5], dtype=torch.int32)

##############tensor 转 list  和  numpy  ##########
[1, 2, 3, 4, 5] [1 2 3 4 5]

  • 14
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值