在块中迭代列表的最“pythonic”方法是什么?我有一个Python脚本,它将整数列表作为输入,我需要一次使用四个整数。不幸的是,我无法控制输入,或者我将它作为四元素元组列表传入。目前,我正在以这种方式迭代它: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-think”,这让我怀疑有更多的pythonic方式来处理这种情况。迭代后会丢弃该列表,因此无需保留。也许这样的事情会更好吗?while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []但是,仍然没有“感觉”正确。: - /相关问题:如何在Python中将列表拆分为大小均匀的块?
4 回答
![?](http://img1.sycdn.imooc.com/545869510001a20b02200220-100-100.jpg)
三国纷争
TA贡献1804条经验 获得超7个赞
![?](http://img1.sycdn.imooc.com/54584e120001811202200220-100-100.jpg)
吃鸡游戏
TA贡献1829条经验 获得超7个赞
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']
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
慕姐8265434
TA贡献1813条经验 获得超2个赞
我是粉丝
chunk_size= 4for i in range(0, len(ints), chunk_size): chunk = ints[i:i+chunk_size] # process chunk of size <= chunk_size
![?](http://img1.sycdn.imooc.com/533e4d470001a00a02000200-100-100.jpg)
红糖糍粑
TA贡献1815条经验 获得超6个赞
import itertoolsdef chunks(iterable,size): it = iter(iterable) chunk = tuple(itertools.islice(it,size)) while chunk: yield chunk chunk = tuple(itertools.islice(it,size))# though this will throw ValueError if the length of ints# isn't a multiple of four:for x1,x2,x3,x4 in chunks(ints,4): foo += x1 + x2 + x3 + x4for chunk in chunks(ints,4): foo += sum(chunk)
其他方式:
import itertoolsdef chunks2(iterable,size,filler=None): it = itertools.chain(iterable,itertools.repeat(filler,size-1)) chunk = tuple(itertools.islice(it,size)) while len(chunk) == size: yield chunk chunk = tuple(itertools.islice(it,size))# x2, x3 and x4 could get the value 0 if the length is not# a multiple of 4.for x1,x2,x3,x4 in chunks2(ints,4,0): foo += x1 + x2 + x3 + x4
添加回答
举报
0/150
提交
取消