开发者

Taking four items instead of on in a for loop [duplicate]

This question already has answers here: How to iterate over a list in chunks (39 answers) Closed 8 months ago.

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 on开发者_开发技巧e?


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)


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']


In one line

x="12345678987654321"
y=[x[i:i+4] for i in range(0,len(x),4)]
print y


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜