簡體   English   中英

list(numpy_array)和numpy_array.tolist()之間的區別

[英]Difference between list(numpy_array) and numpy_array.tolist()

numpy數組上應用list()與調用tolist()之間有什么區別?

我正在檢查兩個輸出的類型,它們都顯示我得到的結果是一個list ,但是,輸出看起來並不完全相同。 是因為list()不是一個特定於numpy方法(即可以應用於任何序列)而tolist() numpy tolist() ,並且在這種情況下它們返回相同的東西?

輸入:

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數組:

>>> 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處理完全轉換為嵌套的vanilla列表(即int listlist ),而list只是迭代數組的第一個維度,創建一個數組listnp.arraynp.int64 list )。 雖然兩者都是列表:

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

每個列表的元素都有不同的類型:

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

正如您所注意到的,另一個區別是list將適用於任何可迭代,而tolist只能在專門實現該方法的對象上調用。

.tolist()似乎遞歸地將所有值轉換為python原語( list ),而list則從iterable list創建python列表。 由於numpy數組是一個數組arrayslist(...)創建一個array list

您可以將list視為一個如下所示的函數:

# Not the actually implementation, just for demo purposes
def  list(iterable):
    newlist = []
    for obj in iter(iterable):
        newlist.append(obj)
    return newlist

主要區別在於tolist遞歸地將所有數據轉換為python標准庫類型。

例如:

>>> arr = numpy.arange(2)
>>> [type(item) for item in list(arr)]
[numpy.int64, numpy.int64]
>>> [type(item) for item in arr.tolist()]
[builtins.int, builtins.int]

除了功能差異之外, tolist通常會更快,因為它知道它有一個numpy數組並且可以訪問支持數組。 然而, list將回退到使用迭代器添加所有元素。

In [2]: arr = numpy.arange(1000)

In [3]: %timeit arr.tolist()
10000 loops, best of 3: 33 µs per loop

In [4]: %timeit list(arr)
10000 loops, best of 3: 80.7 µs per loop

我希望tolist是這樣的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM