0

I have an array of bytes and what I want to do is take four bytes from the array, do something with it and then take the next four bytes. Is it at all possible to do this is a list comprehension or make a for loop take four items from the array instead of one?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
NebulaFox
  • 7,813
  • 9
  • 47
  • 65

4 Answers4

4

Another option is using itertools

http://docs.python.org/library/itertools.html

by using the grouper() method

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
3
def clumper(s, count=4):
    for x in range(0, len(s), count):
        yield s[x:x+count]

>>> list(clumper("abcdefghijklmnopqrstuvwxyz"))
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'yz']
>>> list(clumper("abcdefghijklmnopqrstuvwxyz", 5))
['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'z']
  • Using `range` is correct only if you're using Python 3 (and it's not clear whether the OP wants something *just* for Py3k or also for 2). In Python 2, `range` creates a list full of integers, and you should use `xrange` instead to return an iterator. – Seth Johnson Apr 15 '11 at 12:31
  • The code works fine in both. Using range will still work in Python 2, it just might use more memory. But it will also probably run faster. I'd need to be processing sequences at least tens of millions of items long before I cared. –  Apr 15 '11 at 12:38
  • Why bother using a generator then? – Seth Johnson Apr 15 '11 at 12:39
  • Because I'd only need to be processing a sequence a few dozen thousand items long before I cared about making a list of lists of generic objects, compared to a list of ints. –  Apr 15 '11 at 12:42
2

In one line

x="12345678987654321"
y=[x[i:i+4] for i in range(0,len(x),4)]
print y
jack_carver
  • 1,510
  • 2
  • 13
  • 28
0
suxmac2:Music ajung$ cat xx.py 
lst = range(20)

for i in range(0, len(lst)/4):
    print lst[i*4 : i*4+4]

suxmac2:Music ajung$ python2.5 xx.py
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]