[英]representing list of tuples as 2d array in python
Say I have a list of tuples containing the RGB information of each pixels in an image from left to right, top to bottom. 假设我有一个元组列表,其中包含图像中从左到右,从上到下的每个像素的RGB信息。
[(1,2,3),(2,3,4),(1,2,4),(9,2,1),(1,1,1),(3,4,5)]
Assuming the width and height of the image is already know, is there a way I can represent the image using list of list? 假设图像的宽度和高度是已知的,有没有一种方法可以使用列表列表来表示图像?
For example, let's say the above list of tuples represent a 2x3 image, image[1][2]
should give me the RGB tuple (3,4,5)
. 例如,假设上面的元组列表表示一个2x3图像,
image[1][2]
应该给我RGB元组(3,4,5)
。
Use the step
argument in range
(or xrange
): 在
range
(或xrange
)中使用step
参数:
>>> width = 2
>>> pixels = [(1,2,3),(2,3,4),(1,2,4),(9,2,1),(1,1,1),(3,4,5)]
>>> image = [pixels[x:x+width] for x in range(0,len(pixels),width)]
>>> image
[[(1, 2, 3), (2, 3, 4)], [(1, 2, 4), (9, 2, 1)], [(1, 1, 1), (3, 4, 5)]]
It will make x
increment by the value of the step
, instead of the default, which is 1. If you are familiar with Java, it's similar to: 它将使
x
增加step
的值,而不是默认的值1。如果您熟悉Java,它类似于:
for (int x=0; x<length; x = x+step)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.