tolist()
方法将 NumPy 数组转换为 Python 列表,而不改变其数据或维度。
示例
import numpy as np
array1 = np.array([[0, 1], [2, 3]])
# convert a NumPy array to Python list
list1 = array1.tolist()
print(list1, type(list1))
# Output : [[0, 1], [2, 3]] <class 'list'>
这里,list1 的元素和维度与 array1 相同。
注意:对于一维数组,array1.tolist()
与 list(array1)
相同。
tolist() 语法
tolist()
的语法是
ndarray.tolist()
tolist() 参数
tolist()
方法不接受任何参数。
tolist() 返回值
tolist()
方法返回一个 Python 列表。
示例 1:转换多维数组
tolist()
方法将多维数组转换为嵌套列表。
import numpy as np
array1 = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
# convert the array to list
list1 = array1.tolist()
print(list1)
输出
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
tolist() 与 list() 的区别
tolist()
和 list()
的主要区别是
tolist()
方法将多维数组转换为嵌套列表,而list()
将其转换为数组列表。例如,
import numpy as np
# create a 2-D array
array1 = np.array([[1, 2], [3, 4]])
# convert a 2-D array to nested list
list1 = array1.tolist()
# convert a 2-D array to a list of arrays
list2 = list(array1)
print('Using array.tolist(): ', list1)
print('Using list(array): ', list2)
输出
Using array.tolist(): [[1, 2], [3, 4]] Using list(array): [array([1, 2]), array([3, 4])]
tolist()
将 NumPy 数据类型转换为 Python 数据类型,而list()
则不转换。
import numpy as np
# create a numpy array
array1 = np.array([1, 2])
# convert an array to a list using tolist()
list1 = array1.tolist()
# convert an array to a list using list()
list2 = list(array1)
print("Datatype of original array:", type(array1[0]))
print("Datatype after using array.tolist():", type(list1[0]))
print("Datatype after using array.tolist():", type(list2[0]))
输出
Datatype of original array: <class 'numpy.int64'> Datatype after using array.tolist(): <class 'int'> Datatype after using array.tolist(): <class 'numpy.int64'>
tolist()
可用于 0 维 NumPy 数组,而list()
则不能。
import numpy as np
# create a list of arrays
array1 = np.array(123)
# convert an array to a list using tolist()
list1 = array1.tolist()
print(list1) #123
# convert an array to a list using list()
list2 = list(array1) #TypeError: iteration over a 0-d array
print(list2)
输出
123 TypeError: iteration over a 0-d array