list(numpy_array)和numpy_array.tolist()之间的区别 [英] Difference between list(numpy_array) and numpy_array.tolist()

查看:572
本文介绍了list(numpy_array)和numpy_array.tolist()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy数组上应用list()与调用tolist()有什么区别?

What is the difference between applying list() on a numpy array vs. calling tolist()?

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

I was checking the types of both outputs and they both show that what I'm getting as a result is a list, however, the outputs don't look exactly the same. Is it because that list() is not a numpy-specific method (i.e. could be applied on any sequence) and tolist() is numpy-specific, and just in this case they are returning the same thing?

输入:

points = numpy.random.random((5,2))
print "Points type: " + str(type(points))

输出:

Points type: <type 'numpy.ndarray'>

输入:

points_list = list(points)
print points_list
print "Points_list type: " + str(type(points_list))

输出:

[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''

输入:

points_list_alt = points.tolist()
print points_list_alt
print "Points_list_alt type: " + str(type(points_list_alt))

输出:

[[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''

推荐答案

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

Your example already shows the difference; consider the following 2D array:

>>> 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

tolist 处理全部内容转换为嵌套的香草列表(即intlistlist),而list只是遍历数组的第一维,从而创建数组列表(np.array的list >).虽然都是列表:

tolist handles the full conversion to nested vanilla lists (i.e. list of list of int), whereas list just iterates over the first dimension of the array, creating a list of arrays (list of np.array of np.int64). Although both are lists:

>>> type(list(a))
<type 'list'>
>>> type(a.tolist())
<type 'list'>

每个列表的

元素 具有不同的类型:

the elements of each list have a different type:

>>> type(list(a)[0])
<type 'numpy.ndarray'>
>>> type(a.tolist()[0])
<type 'list'>

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

The other difference, as you note, is that list will work on any iterable, whereas tolist can only be called on objects that specifically implement that method.

这篇关于list(numpy_array)和numpy_array.tolist()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆