2015-06-20 15 views
-3

我有一個類似於thisthat的問題,但這些解決方案是所有列表都「缺乏」區分「而」統一「。簡單的代碼將多個列表組合成一個數組?我其實希望「列表」仍然是該列表中的「列表」

我的Python代碼就像下面:

y = np.empty([1,len(test)]) 
count = -1 
for feature in test : 
    N = engine.neighbours(np.asarray(feature)) 
     if len(N) != 4096: 
      print "error" 
      continue   
     count = count + 1 
    y [count] = engine.neighbours(np.asarray(feature)) 

我只是想知道是否有任何簡單的代碼來完成這項工作?

+0

抱歉代碼寫得不好,這裏是實際的屏幕打印輸出 - http://screencloud.net/v/jhyA – user381509

+0

你的問題似乎與其他問題無關。這些問題是關於將列表壓扁成單個列表。你似乎並不想要那樣。你嘗試過'append'嗎? – nneonneo

+0

感謝您的快速回復。是的,我嘗試過,看起來不太好,雖然我不知道爲什麼結果是沒有,我希望它會產生一個陣列裏面有兩個列表(元素)。 http://screencloud.net/v/hxHT,另一個例子是在這裏http://screencloud.net/v/lRnA謝謝:) – user381509

回答

0

鏈接的問題與扁平列表的列表有關。在你的代碼中,你正在處理一個列表清單(我猜),過濾掉一些,然後收集剩餘的二維數組。

糟糕! y初始化爲1行,但您嘗試將值設置爲y[count],其中count可能會增加至test的大小。

y = np.empty([1,len(test)]) 
count = -1  
# I would prefer to start with 0, but thats a style issue 
for feature in test : 
    N = engine.neighbours(np.asarray(feature)) 
    # so engine.neighbors requires an array; and returns an array? 
     if len(N) != 4096: 
      print "error" 
      continue   
     count = count + 1 
    y [count] = engine.neighbours(np.asarray(feature)) 
    # why call neighbors again? why not reuse N? 

遞增地創建一個數組的一種常見方式是:

alist = [] 
for feature in tests: 
    N = engine.neighbors(np.array(feature) 
    # test N length 
    alist.append(N) 
y = np.array(alist) 

由於由長度測試,所有N具有相同的長度,將得到的陣列將是2D,形狀(n,4096),其中n是具有正確長度的測試次數。

正在初始化ynp.empty((length(tests),4096)],並插入y[count,:] = N可能會更快。如果某些測試未通過測試,您可能會得到未填充的行,但您可以刪除這些行。

初始化ynp.empty((1,4096)],並插入y=np.append(y,N)也應該工作。請注意,此append與附加列表不同。並且變慢。我更喜歡人們直接使用concatenate

y = np.concatenate([y, N[None,:]], axis=0) 

級聯是明確的,以及所需的尺寸操作清晰。

爲了使陣列的一維數組,你必須做這樣的事情:

y=np.empty((4,),dtype=object) 
for i in range(len(y)): 
    y[i]=np.arange(i,2*i) 

生產:

array([array([], dtype=int32), array([1]), array([2, 3]), array([3, 4, 5])], dtype=object) 

這無疑比

產生的 y列表多一點
y=[] 
for i in range(4): 
    y.append(np.arange(i,2*i)) 

在這一切中,我假設engine.neighbors()需要一個1d數組,並返回一個1d數組。如果如果採取/返回多個feature我們可以'矢量化'的東西。但只要我們一次只能給它一個feature,我們就會陷入某種形式的迭代。

相關問題