问题描述
|
我有一个字节数组,我想要做的是从数组中取出四个字节,对其进行处理,然后再取下四个字节。是否可以通过列表理解做到这一点或使for循环从数组中获取四项而不是其中一项?
解决方法
另一种选择是使用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)
,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\']
,一行
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]