Reputation: 71
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)]
Upvotes: 1
Views: 205
Reputation: 943
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.
Upvotes: 2
Reputation: 11922
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)]
Upvotes: 1