1

Say I have a list of tuples containing the RGB information of each pixels in an image from left to right, top to bottom.

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

2
  • 1
    image[x][y] => input_list[x * width + y]. [1][2] becomes [1 * 3 + 2]. Commented Feb 18, 2014 at 16:40
  • So what you're really asking is how to convert a 1d list to a 2d list. Commented Feb 18, 2014 at 16:48

1 Answer 1

2

Use the step argument in range (or xrange):

>>> 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:

for (int x=0; x<length; x = x+step)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.