简体   繁体   English

使用可变长度索引向量在python中创建2D列表

[英]Create 2D lists in python with variable length indexed vectors

I am working on an image processing problem where I have code that looks like this (the code written below just illustrates the type of problem I want to solve): 我正在处理图像处理问题,其中有类似以下的代码(下面编写的代码仅说明了我要解决的问题的类型):

for i in range(0,10):
  for j in range(0,10):
    number_length = round(random.random()*10)
    a = np.zeros(number_length)
    Z[i][j] = a

What I want to do is create some sort of 2D list or np.array (not really sure) where I essentially index a term for every pixel in an image, and have a vector/list of values for every individual pixel of which I can not anticipate its length, moreover, the length of each vector for every indexed pixel is different to each other. 我想做的是创建某种2D列表或np.array(不确定),在这里我实质上为图像中的每个像素索引一个术语,并为每个像素提供一个矢量/值列表此外,由于不能预期其长度,因此每个索引像素的每个矢量的长度都互不相同。 What is the best way to go about this? 最好的方法是什么?

In my MATLAB code the workaround is simple: I define a 2D cell and just assign any vector to any element in the 2D cell. 在我的MATLAB代码中,解决方法很简单:我定义了2D单元,然后将任何矢量分配给2D单元中的任何元素。 Since cells do not complain about coherent length of every indexed vector, this is a good thing. 由于单元格不会抱怨每个索引向量的相干长度,所以这是一件好事。 What is the equivalent optimal solution to handle this in python? 在python中处理此问题的等效最佳解决方案是什么?

Ideally the solution should not involve anticipating the maximum length of "a" for any pixel and to make all indexed vectors the same length (since this implies I have to do some sort of zero padding that will consume memory if the indexed vectors are high dimensional and these high dimensional vectors are sparse through out the image). 理想情况下,解决方案不应涉及预期的最大长度“一”对任何像素,并使得所有索引向量的长度相同(因为这意味着我必须做一些补零如果索引向量是高维会消耗内存并且这些高维向量在整个图像中都是稀疏的)。

A NumPy array won't work because it requires fixed dimensions. NumPy数组不起作用,因为它需要固定的尺寸。 You can use a 2d list (ie list of lists), where each element can be an array of arbitrary length. 您可以使用二维列表(即列表列表),其中每个元素可以是任意长度的数组。 This is analogous to your setup in Matlab, using a 2d cell array of vectors. 这类似于您在Matlab中的设置,使用了矢量的二维单元阵列。

Try this: 尝试这个:

z = [[np.zeros(np.random.randint(10)+1) for j in range(10)] for i in range(10)]

This creates a 10x10 list, where z[i][j] is a NumPy array of zeros with random length (from 1 to 10). 这将创建一个10x10列表,其中z [i] [j]是零长度的NumPy数组,其长度为1至10。

Edit (nested loops requested in comment): 编辑(注释中请求的嵌套循环):

z = [[None for j in range(10)] for i in range(10)]

for i in range(len(z)):
    for j in range(len(z[i])):
        z[i][j] = np.zeros(np.random.randint(10)+1)

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

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