将像素数据嵌套到一个数组中的嵌套数组

问题描述 投票:0回答:2

Example how to order arrays

我有X个在em内具有列表的列表数。因此,我有2个级别的列表需要订购。我需要按哪种顺序排列?

来自此:

[ [[1],[2],[3]], [[1],[2],[3]], [[1],[2],[3]], [[1],[2],[3]] ]

至此

[ [1],[2],[3],[4],[5]... ]

图像更好地描述了我要寻找的内容。

这些内部列表中的每一个都是来自单个图像的像素数据。因此,我想将像素数据从零件排列到一个阵列,该阵列具有所有数据的顺序,就像您在图像中看到的那样。这是我要尝试执行的操作,但不起作用...

# e.g. we have final image 128x128, so we have parts 4 * 64x64

# Empty arrays for every pixel
final_image_pixels = [None] * part_pixel_count * total_parts_count

# Loop through every parts
for i in range(len(image_pixels)):
    for x in range(part_width):                    
        for y in range(part_height):

            # Get location of current pixel
            px_index = x + y * part_width

            # Use pixel loc index for store it to final image
            final_image_pixels[px_index * (i+1)] = image_pixels[px_index]
python arrays list for-loop pixel
2个回答
0
投票

而不是尝试遍历数组索引然后索引到数组,为什么不直接遍历它们?

vals = [ [[1],[2],[3]], [[1],[2],[3]], [[1],[2],[3]], [[1],[2],[3]] ]
result = []
for nested in vals:  # e.g. nested = [[1], [2], [3]]
    for more_nested in nested:  # e.g. more_nested = [1]
        val = more_nested[0]  # e.g. val = 1
        result.append([val])

运行此命令后,result包含:

[[1], [2], [3], [1], [2], [3], [1], [2], [3], [1], [2], [3]]

如果没有必要在输出数组中创建new一条目列表,则可以简化最后两行:

result.append(more_nested)

0
投票

您可以先将此列表弄平,然后再对其进行排序

import itertools 
a = [ [[1],[2],[3]], [[1],[2],[3]], [[1],[2],[3]], [[1],[2],[3]] ]

b = list(itertools.chain(*a)) 
print(sorted(b))

以上代码的输出是:

[[1], [1], [1], [1], [2], [2], [2], [2], [3], [3], [3], [3]]

如果您不想排序,则可以使用

print(list(itertools.chain(*a)))
© www.soinside.com 2019 - 2024. All rights reserved.