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
.
这篇关于什么是最“蟒蛇"?以块为单位迭代列表的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是最“蟒蛇"?以块为单位迭代列表的方法?
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 沿轴计算直方图 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01