Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?
我正在读取一些PNG数据,每像素有4个通道。我想一次迭代数据1个像素(意味着每4个元素=1个像素,rgba)。
red_channel = 0
while red_channel < len(raw_png_data):
green_channel, blue_channel, alpha_channel = red_channel +1, red_channel +2, red_channel +3
# do something with my 4 channels of pixel data ... raw_png_data[red_channel] etc
red_channel += 4
这种方式似乎并不“正确”。有没有一种更像python的方法来迭代一个序列,一次4个条目,并将这4个条目解包?
(Python的itertools应该真正将all recipes作为标准函数…)
您可以使用
grouper
函数:然后你可以通过
或者,你可以使用
注意,如果iterable的长度不是4的倍数,则这将截断最后几个字节。噢,
grouper
函数使用izip_longest
,因此额外的字节将填充为没有。相关问题 更多 >
编程相关推荐