[英]How to add a Numpy Array to a dictionary
How to add two numpy arrays to a dictionary in python ? 如何在python中向字典中添加两个numpy数组?
a = [[1]
[3]]
b = [array([[[ 41., 179.],
[ 451., 254.],
[ 449., 10.],
[ 53., 256.]]], dtype=float32), array([[[ 181., 313.],
[ 27., 24.],
[ 113., 192.],
[ 08., 20.]]], dtype=float32)]
I wish to display a and b as 我希望将a和b显示为
c = {1: array([[ 41., 179.],
[ 451., 254.],
[ 449., 10.],
[ 53., 256.]], dtype=float32),
3: array([[ 181., 313.],
[ 27., 24.],
[ 113., 192.],
[ 08., 20.]], dtype=float32)}
c = dict(zip(a[:,0], b))
would turn your a
and b
variables into a dictionary. c = dict(zip(a[:,0], b))
会将a
和b
变量转换为字典。 I'm not sure whether that's what you're looking for, though. 不过,我不确定这是不是你要找的东西。
Using a dictionary comprehension
: 使用dictionary comprehension
:
I assume you meant to define a
as: 我假设您打算将a
定义为:
a = [1, 3]
then you can get c
with: 然后你可以得到c
:
c = {e: b[i] for i, e in enumerate(a)}
which gives the intended output of: 它给出了预期的输出:
{1: array([[[ 41., 179.],
[ 451., 254.],
[ 449., 10.],
[ 53., 256.]]], dtype=float32),
3: array([[[ 181., 313.],
[ 27., 24.],
[ 113., 192.],
[ 8., 20.]]], dtype=float32)}
If you actually only have a
as a list
of an element
as in [[1], [3]]
, you can do: 如果你确实只有a
作为list
的的element
,如[[1], [3]]
你可以这样做:
a = [i[0] for i in a]
#[[1], [3]] --> [1, 3]
small mistake in c, needs a comma between the two inner lists (are nested lists necessary here?) c中的小错误,需要两个内部列表之间的逗号(这里是否需要嵌套列表?)
Anyways, here is a solution that gives the desired output you want. 无论如何,这里有一个解决方案,可以提供您想要的所需输出。
import numpy as np
c = {}
a = [[1],[3]]
b = [np.array([[[ 41., 179.],
[ 451., 254.],
[ 449., 10.],
[ 53., 256.]]], dtype=np.float32), np.array([[[ 181., 313.],
[ 27., 24.],
[ 113., 192.],
[ 08., 20.]]], dtype=np.float32)]
for i in range(len(a)):
c[a[i][0]] = b[i]
Create a dictionary first (c), then use the values in your nested list a as keys. 首先创建一个字典(c),然后使用嵌套列表中的值作为键。 for each of those keys assign the array in your list b at the same index (i). 对于每个键,在列表b中以相同的索引(i)分配数组。 Do note that this requires that the indexes of a corresponds to the same positions in b. 请注意,这要求a的索引对应于b中的相同位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.