Pythonlist转Tensor

发布时间:2023-05-18

一、Python list 转字符串

Python中,可以使用 join() 方法将列表转换成字符串,然后再使用 tensor 方法将字符串转换成 tensor。

import tensorflow as tf
list_name = ['apple', 'orange', 'mango']
string_name = ' '.join(list_name)
tensor_name = tf.convert_to_tensor(string_name)
print(tensor_name)

二、Python list 转 array

使用 numpy 可以将 Python list 转换成 array,然后再使用 tensorflow 中的 tensor 方法将 array 转换成 tensor。

import tensorflow as tf
import numpy as np
list_name = [1, 2, 3]
array_name = np.array(list_name)
tensor_name = tf.convert_to_tensor(array_name)
print(tensor_name)

三、Python lower 转列表

可以先将 Python lower 转换成一维数组,再使用 tensor 方法将一维数组转化成 tensor。

import tensorflow as tf
lowercase_name = 'abcdefghijklmnopqrstuvwxyz'
list_name = list(lowercase_name)
array_name = [ord(char) - 96 for char in list_name]
tensor_name = tf.convert_to_tensor(array_name)
print(tensor_name)

四、Python np 转 list

使用 numpy 中的 tolist() 方法将 Python np 转化成 Python list,然后再使用 tensor 方法将 Python list 转化成 tensor。

import tensorflow as tf
import numpy as np
np_array = np.array([1, 2, 3])
list_name = np_array.tolist()
tensor_name = tf.convert_to_tensor(list_name)
print(tensor_name)

五、Python list 转文本

可以使用 Python 中的 open() 方法创建一个文本文件,然后将 Python list 写入这个文本文件中,最后再使用 tensor 方法将这个文本文件转化成 tensor。

import tensorflow as tf
list_name = ['apple', 'orange', 'mango']
with open("test.txt", "w") as f:
    for item in list_name:
        f.write("%s\n" % item)
tensor_name = tf.io.read_file("test.txt")
print(tensor_name)

六、Python list 转对象

可以使用 pickle 模块将 Python list 转换成 pickle 格式的对象,然后再使用 tensor 方法将 pickle 对象转换成 tensor。

import tensorflow as tf
import pickle
list_name = ['apple', 'orange', 'mango']
pickle_name = pickle.dumps(list_name)
tensor_name = tf.convert_to_tensor(pickle_name)
print(tensor_name)

七、Python int 转 str

可以将 Python int 转换成 Python str,再使用 tensor 方法将 Python str 转换成 tensor。

import tensorflow as tf
int_name = 123
str_name = str(int_name)
tensor_name = tf.convert_to_tensor(str_name)
print(tensor_name)

八、Python json 转 str

使用 json 模块将 Python list 转换成 Python str 格式,然后再使用 tensor 方法将 Python str 转换成 tensor。

import tensorflow as tf
import json
list_name = ['apple', 'orange', 'mango']
json_name = json.dumps(list_name)
tensor_name = tf.convert_to_tensor(json_name)
print(tensor_name)

九、Python 怎么转 string

可以将 Python 中的基本数据类型转化成 Python str 类型,然后再使用 tensor 方法将 Python str 转换成 tensor。

import tensorflow as tf
data = 123
string_data = str(data)
tensor_data = tf.convert_to_tensor(string_data)
print(tensor_data)

十、Python 中 list 转 row

使用 numpy 中的 reshape() 方法可以将 Python list 转换成 Python array,然后根据需要,将 Python array 转换成 row,最后再使用 tensor 方法将 row 转换成 tensor。

import tensorflow as tf
import numpy as np
list_name = [1, 2, 3, 4, 5, 6]
array_name = np.array(list_name)
row_name = np.reshape(array_name, (1, -1))
tensor_name = tf.convert_to_tensor(row_name)
print(tensor_name)