2

我想存儲一個2-d數組作爲共享內存數組,所以每個由多處理模塊創建的進程都可以訪問2-d數組。但似乎只有矢量是允許的。如果我將以下示例中的形狀從(6,1)更改爲(2,3),該示例將不起作用,並且它會顯示「TypeError:只能將長度爲1的數組轉換爲Python標量」python多處理共享內存數組不允許二維數組

from multiprocessing import Process, Value, Array 
import numpy as np 

def f(n,a): 
    a[:] = np.ones(shape=(6,1), dtype=float)[:] 

if __name__ == '__main__': 
    tmp = np.zeros(shape=(6,1), dtype=float) 
    print tmp 

    arr = Array('f', tmp) 

    p1 = Process(target=f, args=(1,arr)) 
    p1.start() 
    p1.join() 

    print 'done' 
    print arr[:] 

回答

3

這是因爲mutiprocessing.Array是python的array類型的包裝,而不是numpy.ndarray和python的array類型不支持多維度。具體而言,看爲initializer的文檔:

A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, string, or iterable over elements of the appropriate type.

你有一個可迭代(多維陣列),但它產生的觀點/陣列,適當類型的不元件。

+0

有沒有一種快速的方法將numpy.ndarray轉換爲數組? –

+0

@readRead - 只有一維numpy數組可以轉換爲'array' - 它會複製(不是視圖) – mgilson

+0

謝謝。我打算對每個進程中的共享數組執行一些矩陣操作。如果我只是存儲一維數組,這不是很方便。如何跨進程共享一個2-D numpy陣列並避免複製?也許使用除多處理以外的其他東西。數組? –