Python:连接存储在字典中的数组

问题描述 投票:0回答:3

我有一个大字典,存储以下数组:

Store = dict()
Store['A'] = A #size 500x30
Store['B'] = B #size 500x20

我只有 A 和 B 来说明。在我目前的现实生活中,我使用的字典中有大约 500 个键和值。

我想以一种优雅的方式连接数组以获得数组C。

为了说明,这就是我想要实现的目标:

A = np.random.normal( 0, 1, ( 500, 20 ) )
B = np.random.normal( 0, 1, ( 500, 30 ) )
C = np.concatenate((A,B),1)
python numpy
3个回答
7
投票

如果顺序不重要,请将字典的值传递给

numpy.concatenate

>>> store = {'A':np.array([1,2,3]), 'B':np.array([3,4,5])}
>>> np.concatenate(store.values(),1)
array([1, 2, 3, 3, 4, 5])

如果顺序很重要,您可以使用

np.concatenate([v for k,v in sorted(store.items(), key=...)], 1)

传入您喜欢的任何键函数,或者如果您想按字典顺序排序,则将键参数省略。可悲的是,

concatenate
似乎没有采用生成器对象。


7
投票

np.concatenate([Store[x] for x in Store], 1)

np.concatenate([Store[x] for x in sorted(Store)], 1)
如果顺序很重要。


0
投票

抱歉,无法发表评论(新用户),但 @Stuchfield 的答案适用于我的 python 版本!

© www.soinside.com 2019 - 2024. All rights reserved.