使用可变长度索引向量在python中创建2D列表 [英] Create 2D lists in python with variable length indexed vectors

查看:106
本文介绍了使用可变长度索引向量在python中创建2D列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个图像处理问题,其中的代码如下所示(下面编写的代码仅说明了我要解决的问题的类型):

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

我想做的是创建某种2D列表或np.array(不确定),其中我实质上为图像中每个像素索引一个术语,并为每个像素的每个像素都有一个矢量/值列表我无法预料到它的长度,而且,每个索引像素的每个向量的长度都互不相同.最好的方法是什么?

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. What is the best way to go about this?

在我的MATLAB代码中,解决方法很简单:我定义了2D单元格,只需将任何矢量分配给2D单元格中的任何元素.由于单元格不会抱怨每个索引向量的相干长度,所以这是一件好事.在python中处理此问题的等效最佳解决方案是什么?

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. 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?

理想情况下,解决方案应该涉及预测任何像素的"a​​"的最大长度,并使所有索引向量的长度相同(因为这意味着我必须进行某种零填充,即如果索引向量是高维的并且这些高维向量在整个图像中都是稀疏的,则会消耗内存.

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

推荐答案

NumPy数组不起作用,因为它需要固定的尺寸.您可以使用二维列表(即列表列表),其中每个元素可以是任意长度的数组.这类似于您在Matlab中的设置,使用了矢量的二维单元阵列.

A NumPy array won't work because it requires fixed dimensions. You can use a 2d list (i.e. 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.

尝试一下:

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

这将创建一个10x10列表,其中z [i] [j]是一个零长度的NumPy数组,其长度为1至10.

This creates a 10x10 list, where z[i][j] is a NumPy array of zeros with random length (from 1 to 10).

编辑(在注释中请求嵌套循环):

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)

这篇关于使用可变长度索引向量在python中创建2D列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆