2016-12-04 130 views
0

爲什麼不附加所有列表?Numpy append數組不工作

test = {'file1':{'subfile1':[1,2,3],'subfile2':[10,11,12]},'file5':{'subfile1':[4,678,6]},'file2':{'subfile1':[4,78,6]},'file3':{'subfile1':[7,8,9]}} 
testarray = np.array([50,60,70]) 
for file in test.keys(): 
    print(test[file]['subfile1']) 
    subfile1 = np.append(testarray, test[file]['subfile1']) 
print(subfile1) 
+1

它在做什麼?不要只顯示代碼。顯示結果並解釋什麼是錯誤的。 – hpaulj

回答

0

numpy.append回報新NumPy的陣列,而你的代碼顯示,你認爲這是增加新的值testarray。該陣列不附加在原地,新陣列必須被創建並填充數據,因此複製testarraytest[file]['subfile1']

此外,請注意,不需要循環使用鍵並通過其中一個鍵從字典中提取值。你也可以遍歷的項目數組包含,包括鍵和值:

for key, value in test.items(): 
    print(value['subfile1']) 
    ... 
0

而不是反覆串聯列表到一個數組,收集在一個列表中的值,並構建陣列一次。這是更快,不易出錯:

In [514]: test 
Out[514]: 
{'file1': {'subfile1': [1, 2, 3], 'subfile2': [10, 11, 12]}, 
'file2': {'subfile1': [4, 78, 6]}, 
'file3': {'subfile1': [7, 8, 9]}, 
'file5': {'subfile1': [4, 678, 6]}} 
In [515]: data=[test[f]['subfile1'] for f in test] 
In [516]: data 
Out[516]: [[1, 2, 3], [4, 78, 6], [7, 8, 9], [4, 678, 6]] 
In [517]: np.array(data) 
Out[517]: 
array([[ 1, 2, 3], 
     [ 4, 78, 6], 
     [ 7, 8, 9], 
     [ 4, 678, 6]]) 

如果你一定要,建立反覆名單:

In [521]: testarray=np.array([50,60,70]) 
In [522]: for file in test.keys(): 
    ...:  testarray = np.concatenate((testarray, test[file]['subfile1'])) 
    ...:  
In [523]: testarray 
Out[523]: 
array([ 50, 60, 70, 1, 2, 3, 4, 78, 6, 7, 8, 9, 4, 678, 6]) 

注意這使:

In [518]: data=[] 
In [519]: for f in test.keys(): 
    ...:  data.append(test[f]['subfile1']) 

你可以在每一步串聯所有值都在一個1d數組中,而不是前面方法所做的2d數組。我們可以vstack去2d(它也使用concatenate)。我可以寫append,但我寧願不要。太多海報誤用了它。