我有一个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",这让我怀疑有一种更具蟒蛇风格的方式来处理这种情况。该列表在迭代后被丢弃,因此不需要保留。也许像这样的东西会更好?
while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []然而,仍然不太“感觉”正确。:-/
相关问题:How do you split a list into evenly sized chunks in Python?
发布于 2009-01-12 04:07:21
发布于 2009-01-12 03:10:18
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
# (in python 2 use xrange() instead of range() to avoid allocating a list)适用于任何序列:
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']发布于 2009-01-12 03:06:09
chunk_size = 4
for i in range(0, len(ints), chunk_size):
chunk = ints[i:i+chunk_size]
# process chunk of size <= chunk_sizehttps://stackoverflow.com/questions/434287
复制相似问题