Python 将列表拆分为 n 个块 [英] Python split list into n chunks

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

问题描述

我知道这个问题已经讨论过很多次了,但我的要求是不同的.

我有一个类似的列表:range(1, 26).我想把这个列表分成一个固定的数字n.假设 n = 6.

<预><代码>>>>X[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]>>>l = [ x [i:i + 6] for i in range(0, len(x), 6) ]>>>升[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21,22, 23, 24], [25]]

如您所见,我没有得到 6 个块(包含原始列表元素的六个子列表).我如何以这样一种方式划分列表,以便我得到准确的 n 块,这些块可能是均匀的或不均匀的

解决方案

使用 numpy

<预><代码>>>>导入 numpy>>>x = 范围(25)>>>l = numpy.array_split(numpy.array(x),6)

<预><代码>>>>导入 numpy>>>x = numpy.arange(25)>>>l = numpy.array_split(x,6);

您也可以使用 numpy.split 但如果长度不能完全整除,则会出错.

I know this question has been covered many times but my requirement is different.

I have a list like: range(1, 26). I want to divide this list into a fixed number n. Assuming n = 6.

>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
>>> l = [ x [i:i + 6] for i in range(0, len(x), 6) ]
>>> l
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24], [25]]

As you can see I didn't get 6 chunks (six sublists with elements of original list). How do I divide a list in such a way that I get exactly n chunks which may be even or uneven

解决方案

Use numpy

>>> import numpy
>>> x = range(25)
>>> l = numpy.array_split(numpy.array(x),6)

or

>>> import numpy
>>> x = numpy.arange(25)
>>> l = numpy.array_split(x,6);

You can also use numpy.split but that one throws in error if the length is not exactly divisible.

这篇关于Python 将列表拆分为 n 个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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