1

I have a list like this

[255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 127, 0, 255, 127, 0, 255, 127, 0, 255, 127, 0, 255, 127, 0, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255]

What is a best way to convert to pair of 3 (rgb), inside is tuple

pixel = [(255,0,0),(255,0,0),(255,0,0),(255,0,0),(127,0,255),(127,0,255),(127,0,255),(127,0,255),(127,0,255),(0,127,255),(0,127,255),(0,127,255),(0,127,255),(0,127,255),(0,127,255),(0,127,255)]
Juhil Somaiya
  • 873
  • 7
  • 20
fastmen111
  • 69
  • 2
  • 9
  • 2
    Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Riccardo Bucco Nov 22 '19 at 09:20

2 Answers2

2

you can simply use the iter() as below:

RGB = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 127, 0, 255, 127, 0, 255, 127, 0, 255, 127, 0, 255, 127, 0, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255]
it = iter(RGB)
print(list(zip(it,it,it)))

if you want a group of N elements in tuple you can simply use the zip(it * N) and you will get the N number of elements in a tuple.

Juhil Somaiya
  • 873
  • 7
  • 20
1

Using numpy is very easy in this case:

import numpy as np
pixels = [255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 127, 0, 255, 127, 0, 255, 127, 0, 255, 127, 0, 255, 127, 0, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255, 0, 127, 255]
np_pixels = np.array(pixels).reshape((-1, 3))
print(np_pixels)

Output:

>>> print(np_pixels)
[[255   0   0]
 [255   0   0]
 [255   0   0]
 [255   0   0]
 [127   0 255]
 [127   0 255]
 [127   0 255]
 [127   0 255]
 [127   0 255]
 [  0 127 255]
 [  0 127 255]
 [  0 127 255]
 [  0 127 255]
 [  0 127 255]
 [  0 127 255]
 [  0 127 255]]

If you insist on making them tuples you can just do this afterwards:

np_pixels = [tuple(row) for row in np_pixels]

Output:

[(255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (127, 0, 255), (127, 0, 255), (127, 0, 255), (127, 0, 255), (127, 0, 255), (0, 127, 255), (0, 127, 255), (0, 127, 255), (0, 127, 255), (0, 127, 255), (0, 127, 255), (0, 127, 255)]
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62