Newbie looking for elegant solution

Dave Farrance DaveFarrance at OMiTTHiSyahooANDTHiS.co.uk
Wed Mar 25 02:05:45 EDT 2015


otaksoftspamtrap at gmail.com wrote:

>I have a list containing 9600 integer elements - each integer is either 0 or 1.
>Starting at the front of the list, I need to combine 8 list elements into 1 by treating them as if they were bits of one byte with 1 and 0 denoting bit on/off (the 8th element would be the rightmost bit of the first byte).
>The end result should be a new list that is 8 x shorter than the original list containing integers between 0 and 255.
>Speed is not of utmost importance - an elegant solution is. Any suggestions?
>Thanks for all input,

Here's another way. Works in Python 2 and 3.

>>> x = [1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1]
>>> [int(''.join( str(y) for y in x[z:z+8]),2) for z in range(0, len(x), 8)]
[177, 105, 117]



More information about the Python-list mailing list