而不是反覆串聯列表到一個數組,收集在一個列表中的值,並構建陣列一次。這是更快,不易出錯:
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
,但我寧願不要。太多海報誤用了它。
它在做什麼?不要只顯示代碼。顯示結果並解釋什麼是錯誤的。 – hpaulj