Python中 各种类型的相互转换
list与numpy相互转换
list 转 numpy
ndarray = np.array(list)
numpy 转 list
list = ndarray.tolist()
list 转 torch.Tensor
tensor=torch.Tensor(list)
Tensor与list,numpy的相互转换
torch.Tensor 转 list
# 先转numpy,后转list
list = tensor.numpy().tolist()
torch.Tensor 转 numpy
ndarray = tensor.numpy()
gpu上的tensor不能直接转为numpy
ndarray = tensor.cpu().numpy()
numpy 转 torch.Tensor
tensor = torch.from_numpy(ndarray)
list 与 str 的相互转换
list -> str
- 方法: ''.join(list)
其中,引号中是用于分割字符的符号,如“,”,“;”,“\t”等等
- 示例
>>> a = 'abc'
>>> a_str = ''.join(a)
>>> a_str
'abc'
>>> type(a_list)
str
>>> a_str = ','.join(a)
>>> a_str
'a,b,c'
str -> list
list(str)
- 示例
>>> s = 'abcde'
>>> s_list = list(s)
>>> s_list
['a', 'b', 'c', 'd', 'e']
>>> type(s_list)
list
str.split()
>>> a = '123 4'
>>> b = list(a)
>>> b
['1', '2', '3', ' ', ' ', '4']
# split()默认以空白区域为分割
>>> c = a.split()
>>> c
['123', '4']
# 以 空格 为分割,值得注意的是,分割后的字符串中包含空格本身
>>> d = a.split(' ')
>>> d
['123', '', '4']
字符串类型数组 -> 整型数组
- 方法:list(map(type,arr))
>>> arr = ['1', '2', '3', '4']
# arr = map(int, arr)
# arr
# <map object at 0x0000018DC5DCFA90>
# list(arr)
# [1, 2, 3, 4]
>>> arr_i = list(map(int,arr))
>>> arr_i
[1, 2, 3, 4]