创建包含可变大小数组的词典列表

2024-03-28 16:25:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

具有相同两个键“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计数器访问它。你知道吗


Tags: 数据图像numpy示例数据结构列表output字典
2条回答

我假设输入的长度列表是一个成对的列表,或者类似的东西。你知道吗

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是一个字典列表,每个字典都有两个键;每个值都是一个没有所需长度的列表。你知道吗

关于:

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)]

相关问题 更多 >