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

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

问题描述

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

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.

相关问题:

推荐答案

这里有一个生成器,可以生成您想要的块:

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():


If you're using Python 2, you should use xrange() instead of 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]


您也可以简单地使用列表推导而不是编写函数,尽管将这样的操作封装在命名函数中是一个好主意,这样您的代码更易于理解. Python 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天全站免登陆