【问题标题】:Creating an list of dictionaries that hold a variable sized array创建包含可变大小数组的字典列表
【发布时间】:2016-12-08 14:56:41
【问题描述】:

我正在尝试创建以下数据结构(我知道这不是最佳的,但考虑到我的输入数据是必要的):

具有相同两个键“x”和“y”的 100 个字典的列表,其中每个键包含一个可变长度的 numpy 数组。 “y”包含一个向量,“x”包含一个图像数组,因此 x 的示例形状可以是 10 x 3 x 10 x 50,或者 10 个大小为 10 x 50 的 RGB 图像。对应 y 的示例形状将是 10,因为 x 和 y 的初始长度必须相同。如果我只有 8 张图片,那么 y 的长度也是 8 等等。

我想预初始化这个结构,以便我可以用更改的数据值填充它,并这样做以便我可以根据单独的片段为每个字典设置可变长度“x”和“y”数组的大小的输入数据。我知道我可以这样设置字典:

imageArray = np.zeros(10,3,10,50)

vectorNumbers = np.zeros(10)

output = [{'x':imageArray,'y':vectorNumbers}]

所以应该创建一个字典,但是如果我有一个数组,其中字典值“x”和“y”的长度,我该如何使用这样的东西:

 output = [{'x':imageArray,'y':vectorNumbers} for k in range(listLength)]

但请确保 imageArray 的长度为 [variable,3,10,50],vectorNumbers 的长度为 [variable],其中 variable 是存储在另一个列表中的数字,我可以通过上面的 k 计数器访问它。

【问题讨论】:

  • 这会将相同的数组放入每个字典中。更改一个值将更改所有值。我不认为你想要那个。您需要为每个字典创建一个具有正确尺寸的新数组。使用列表和字典,您不能走捷径。

标签: python arrays list numpy dictionary


【解决方案1】:

我假设输入的长度列表是对的列表,或者类似的东西。

input_lengths = [(12,17), (8,50), (2,7)]
pre_filled_list = [{'x' : [None]*x, 'y' : [None]*y} for x,y in input_lengths]
print(pre_filled_list)

pre_filled list 是一个字典列表,每个都有两个键;每个值都是所需长度的 None 列表。

【讨论】:

  • xy 应该是 4d 和 1d numpy 数组,而不是列表。
【解决方案2】:

怎么样:

import numpy as np

dims = [(42,43), (46,9), (47,49), (60,14)]
output = [{'x':np.zeros((x,3,10,50)), 'y':np.zeros((y,))} for (x,y) in dims]

print(len(output))              # 4, matches len(dims)

print(type(output[0]['x']))     # <type 'numpy.ndarray'>
print(type(output[0]['y']))     # <type 'numpy.ndarray'>

print(output[0]['x'].shape)     # (42, 3, 10, 50)
                                #  42 is from the first element of the first tuple in dims
print(output[0]['y'].shape)     # (43,)
                                #  43 is from the second element of the first tuple in dims

print(output[1]['x'].shape)     # (46, 3, 10, 50)
print(output[1]['y'].shape)     # (9,)

数组在字典中,字典在列表中。您想要的尺寸(我认为)的所有零。

如果你想要更接近你所拥有的东西,使用range(listLength),这四行会产生与上面相同的输出:

xd = [42, 46, 47, 60]
yd = [43,  9, 49, 14]
listLength = 4

output=[{'x':np.zeros((xd[k],3,10,50)),'y':np.zeros((yd[k],))} for k in range(listLength)]

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2014-04-09
    • 2019-06-28
    • 2014-08-13
    • 2017-10-08
    • 2013-04-09
    相关资源
    最近更新 更多