我有一个 Python 脚本,它将整数列表作为输入,我需要一次处理四个整数。不幸的是,我无法控制输入,否则我会将其作为四元素元组列表传入。目前,我正在以这种方式迭代它:
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”,这让我怀疑有一种更pythonic的方式来处理这种情况。该列表在迭代后被丢弃,因此无需保留。也许这样的东西会更好?
while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []
不过,仍然不太“感觉”对。:-/
相关问题:如何在 Python 中将列表拆分为大小均匀的块?
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
适用于任何序列:
text = "I am a very, very helpful text"
for group in chunker(text, 7):
print(repr(group),)
# 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'
print('|'.join(chunker(text, 10)))
# I am a ver|y, very he|lpful text
animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']
for group in chunker(animals, 3):
print(group)
# ['cat', 'dog', 'rabbit']
# ['duck', 'bird', 'cow']
# ['gnu', 'fish']
修改自 Python 文档的 Rerecies 部分:itertools
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
chunk_size = 4
for i in range(0, len(ints), chunk_size):
chunk = ints[i:i+chunk_size]
# process chunk of size <= chunk_size
模板简介:该模板名称为【Python如何在块中迭代列表】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。