什么是最"pythonic"的?遍历列表的一种方法? [英] What is the most "pythonic" way to iterate over a list in chunks?
问题描述
我有一个Python脚本,该脚本接受一个整数列表作为输入,我需要一次处理四个整数.不幸的是,我无法控制输入,或者将其作为四元素元组的列表传递.目前,我正在以这种方式对其进行迭代:
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:
for i in xrange(0, len(ints), 4):
# dummy op for example code
foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]
不过,它看起来很像"C思维",这使我怀疑还有一种处理这种情况的更Python的方法.列表在迭代后被丢弃,因此不需要保留.也许像这样会更好?
It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?
while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []
尽管如此,还是不太正确". :-/
Still doesn't quite "feel" right, though. :-/
相关问题:如何操作您将列表拆分成Python中大小均匀的块吗?
推荐答案
从 itertools docs的>食谱" 部分:
Modified from the recipes section of Python's itertools docs:
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
示例
用伪代码保持示例简洁.
Example
In pseudocode to keep the example terse.
grouper('ABCDEFG', 3, 'x') --> 'ABC' 'DEF' 'Gxx'
注意:在Python 2上,请使用izip_longest
代替zip_longest
.
Note: on Python 2 use izip_longest
instead of zip_longest
.
这篇关于什么是最"pythonic"的?遍历列表的一种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!