在for循环中取四个项而不是on

时间:2011-04-15 11:53:32

标签: python python-3.x

我有一个字节数组,我想要做的是从数组中取四个字节,用它做一些事情然后接下来的四个字节。是否可以做到这一点是一个列表理解或使一个for循环从数组中取出四个项而不是一个?

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:4)

另一种选择是使用itertools

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

使用grouper()方法

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

答案 2 :(得分:3)

在一行

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

答案 3 :(得分: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]