list(numpy_array)和numpy_array.tolist()之间的区别

ato*_*ozh 6 python arrays numpy list

是什么应用之间的区别list()一对numpy阵列与调用tolist()

我正在检查两个输出的类型,它们都显示我得到的结果是list,但是,输出看起来并不完全相同.是因为那list()不是一个numpy特定的方法(即可以应用于任何序列)并且tolist() numpy特定的,并且只是在这种情况下它们返回相同的东西?

输入:

points = numpy.random.random((5,2))
print "Points type: " + str(type(points))
Run Code Online (Sandbox Code Playgroud)

输出:

Points type: <type 'numpy.ndarray'>
Run Code Online (Sandbox Code Playgroud)

输入:

points_list = list(points)
print points_list
print "Points_list type: " + str(type(points_list))
Run Code Online (Sandbox Code Playgroud)

输出:

[array([ 0.15920058,  0.60861985]), array([ 0.77414769,  0.15181626]), array([ 0.99826806,  0.96183059]), array([ 0.61830768,  0.20023207]), array([ 0.28422605,  0.94669097])]
Points_list type: 'type 'list''
Run Code Online (Sandbox Code Playgroud)

输入:

points_list_alt = points.tolist()
print points_list_alt
print "Points_list_alt type: " + str(type(points_list_alt))
Run Code Online (Sandbox Code Playgroud)

输出:

[[0.15920057939342847, 0.6086198537462152], [0.7741476852713319, 0.15181626186774055], [0.9982680580550761, 0.9618305944859845], [0.6183076760274226, 0.20023206937408744], [0.28422604852159594, 0.9466909685812506]]

Points_list_alt type: 'type 'list''
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 9

你的例子已经显示出差异 ; 考虑以下2D数组:

>>> import numpy as np
>>> a = np.arange(4).reshape(2, 2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.tolist()
[[0, 1], [2, 3]] # nested vanilla lists
>>> list(a)
[array([0, 1]), array([2, 3])] # list of arrays
Run Code Online (Sandbox Code Playgroud)

tolist处理完全转换为嵌套的vanilla列表(即listof listof int),而list只是迭代数组的第一维,创建一个数组列表(listof np.arrayof np.int64).虽然两者都是列表:

>>> type(list(a))
<type 'list'>
>>> type(a.tolist())
<type 'list'>
Run Code Online (Sandbox Code Playgroud)

每个列表的元素都有不同的类型:

>>> type(list(a)[0])
<type 'numpy.ndarray'>
>>> type(a.tolist()[0])
<type 'list'>
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,另一个区别是,list它将适用于任何可迭代的,而tolist只能在专门实现该方法的对象上调用.