> On Mar 24, 2015, at 8:28 PM, Chris Angelico <ros...@gmail.com> wrote: > > On Wed, Mar 25, 2015 at 2:13 PM, <otaksoftspamt...@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). >> >> Speed is not of utmost importance - an elegant solution is. Any suggestions? > > Oooh fun! > >>>> l = [1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, >>>> 1] >>>> list(int(''.join(str(i) for i in l),2).to_bytes(len(l)//8,'big')) > [177, 105, 117] > > Convert it into a string, convert the string to an integer > (interpreting it as binary), then convert the integer into a series of > bytes, and interpret those bytes as a list of integers. > > Example works in Python 3. For Python 2, you'll need ord() to get the > integers at the end. > > I'm not sure how elegant this is, but it's a fun trick to play with :) > > Next idea please! I love these kinds of threads.
Me too. These are my favorite threads. Here’s my entry: [sum(b << (7 - i) for i, b in enumerate(bits)) for bits in zip(*[l[n::8] for n in range(8)])] I think there has to be a better way to do the left hand part, but I liked the zipped iterators on 8 slices. -- https://mail.python.org/mailman/listinfo/python-list