你如何将一个列表分成大小均匀的块? [英] How do you split a list into evenly sized chunks?

查看:35
本文介绍了你如何将一个列表分成大小均匀的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任意长度的列表,我需要将它分成相等大小的块并对其进行操作.有一些明显的方法可以做到这一点,例如保留一个计数器和两个列表,当第二个列表填满时,将其添加到第一个列表并清空第二个列表以供下一轮数据使用,但这可能非常昂贵.

I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.

我想知道是否有人对任何长度的列表有很好的解决方案,例如使用生成器.

I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.

我在 itertools 中寻找一些有用的东西,但我找不到任何明显有用的东西.不过可能已经错过了.

I was looking for something useful in itertools but I couldn't find anything obviously useful. Might've missed it, though.

相关问题:以块为单位迭代列表的最pythonic"方式是什么?

推荐答案

这是一个生成你想要的块的生成器:

Here's a generator that yields the chunks you want:

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

<小时>

import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74]]

<小时>

如果你使用 Python 2,你应该使用 xrange() 而不是 range():

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in xrange(0, len(lst), n):
        yield lst[i:i + n]

<小时>

您也可以简单地使用列表推导而不是编写函数,尽管将这样的操作封装在命名函数中是个好主意,这样您的代码更容易理解.蟒蛇 3:


Also you can simply use list comprehension instead of writing a function, though it's a good idea to encapsulate operations like this in named functions so that your code is easier to understand. Python 3:

[lst[i:i + n] for i in range(0, len(lst), n)]

Python 2 版本:

Python 2 version:

[lst[i:i + n] for i in xrange(0, len(lst), n)]

这篇关于你如何将一个列表分成大小均匀的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆