与其重复地将列表连接到一个数组,不如收集一个列表中的值,然后只构建一次数组。它更快,更不容易出错:
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 [518]: data=[]
In [519]: for f in test.keys():
...: data.append(test[f]['subfile1'])
你可以在每一步连接:
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])
请注意,这会将所有值放在一个 1d 数组中,而不是之前的方法所做的 2d 数组。我们可以vstack 去二维(它也使用concatenate)。
In [525]: testarray=np.array([50,60,70])
In [526]: for file in test.keys():
...: testarray = np.vstack((testarray, test[file]['subfile1']))
...:
...:
In [527]: testarray
Out[527]:
array([[ 50, 60, 70],
[ 1, 2, 3],
[ 4, 78, 6],
[ 7, 8, 9],
[ 4, 678, 6]])
我也可以用append 来写这个,但我不想这样做。太多海报滥用它。