简体   繁体   English

Python dictionary.values()到numpy数组

[英]Python dictionary.values() to numpy array

Say I have a dict using python 3: 假设我有一个使用python 3的字典:

d = {'w1': np.array([12,11,23]), 'w2':np.array([1,2,3])}

and some variable with an integer say 还有一些带有整数的变量说

a=12

How do I turn the dict values and integer into one numpy array so that it looks like this? 如何将dict值和整数转换为一个numpy数组,使其看起来像这样?

array([12, array([12, 11, 23]), array([1, 2, 3])])

I've tried: 我试过了:

np.array([a,(list(d.values()))],dtype=object)

and I get: 我得到:

array([12, list([array([12, 11, 23]), array([1, 2, 3])])], dtype=object)

but I don't want the list in the second index, I want it to be "unpacked". 但我不希望列表包含在第二个索引中,而是希望它被“解压”。

If you don't want to put the arrays in an inner list, just don't put them in a list: 如果您不想将数组放在内部列表中,只需不要将它们放在列表中:

>>> np.array([a, *d.values()], dtype=object)
array([12, array([12, 11, 23]), array([1, 2, 3])], dtype=object)

Or, if you're on an older Python and can't unpack into a list display, create the list, but add it to another one to get the same flat list: 或者,如果您使用的是较旧的Python,并且无法解压缩到列表显示中,请创建列表,然后将其添加到另一个列表中以获得相同的平面列表:

>>> np.array([a] + list(d.values()), dtype=object)
array([12, array([12, 11, 23]), array([1, 2, 3])], dtype=object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM