正如其他人所写,list() 之所以有效,是因为数组是可迭代的。它相当于[i for i in arr]。要理解它,您需要了解数组上的迭代是如何工作的。特别是list(arr) 与arr.tolist() 不同。
In [685]: arr=np.array('one two three four'.split())
In [686]: arr
Out[686]:
array(['one', 'two', 'three', 'four'],
dtype='<U5')
In [687]: ll=list(arr)
In [688]: ll
Out[688]: ['one', 'two', 'three', 'four']
In [689]: type(ll[0])
Out[689]: numpy.str_
In [690]: ll1=arr.tolist()
In [691]: ll1
Out[691]: ['one', 'two', 'three', 'four']
In [692]: type(ll1[0])
Out[692]: str
ll 和ll1 的打印显示看起来一样,但元素的type 不同,一个是str,另一个是包裹在numpy 类中的str。这种区别出现在最近关于序列化数组的问题中。
arr 为 2d 时,区别变得更加明显。然后简单的交互产生行,而不是元素:
In [693]: arr=np.reshape(arr,(2,2))
In [694]: arr
Out[694]:
array([['one', 'two'],
['three', 'four']],
dtype='<U5')
In [695]: list(arr)
Out[695]:
[array(['one', 'two'],
dtype='<U5'), array(['three', 'four'],
dtype='<U5')]
In [696]: arr.tolist()
Out[696]: [['one', 'two'], ['three', 'four']]
list(arr) 现在是两个数组,而arr.tolist() 是一个嵌套列表。
Python Pandas: use native types
Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works