什么是最“蟒蛇"?以块为单位迭代列表的方法?

What is the most quot;pythonicquot; 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 range(0, len(ints), 4):
    # dummy op for example code
    foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]

不过,它看起来很像C-think",这让我怀疑有一种更 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 文档的 >Recipes 部分:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

示例

grouper('ABCDEFG', 3, 'x')  # --> 'ABC' 'DEF' 'Gxx'

注意:在 Python 2 上使用 izip_longest 而不是 zip_longest.

Note: on Python 2 use izip_longest instead of zip_longest.

这篇关于什么是最“蟒蛇"?以块为单位迭代列表的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:什么是最“蟒蛇"?以块为单位迭代列表的方法?

基础教程推荐