为了账号安全,请及时绑定邮箱和手机立即绑定

在块中迭代列表的最“pythonic”方法是什么?

在块中迭代列表的最“pythonic”方法是什么?

忽然笑 2019-05-27 10:19:51
在块中迭代列表的最“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 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

从Python的itertools文档的recipes部分修改:

from itertools import zip_longestdef 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


查看完整回答
反对 回复 2019-05-27
?
吃鸡游戏

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']


查看完整回答
反对 回复 2019-05-27
?
慕姐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


查看完整回答
反对 回复 2019-05-27
?
红糖糍粑

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


查看完整回答
反对 回复 2019-05-27
  • 4 回答
  • 0 关注
  • 538 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信