如何在python中将列表拆分为给定数量的子列表 [英] How to split a list into a given number of sub-lists in python

查看:469
本文介绍了如何在python中将列表拆分为给定数量的子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
将任意大小的列表拆分为仅大约N个相等的部分
如何将列表平均划分大小的Python块?

Possible Duplicates:
splitting a list of arbitrary size into only roughly N-equal parts
How do you split a list into evenly sized chunks in Python?

我需要创建一个将列表分成列表列表的函数,每个列表包含相等数量的项目(或尽可能相等).

I need to create a function that will split a list into a list of list, each containing an equal number of items (or as equal as possible).

例如

def split_lists(mainlist, splitcount):
    ....


mylist = [1,2,3,4,5,6]

split_list(mylist,2)将返回包含三个元素的两个列表的列表-[[1,2,3][4,5,6]].

split_list(mylist,2) will return a list of two lists of three elements - [[1,2,3][4,5,6]].

split_list(mylist,3)将返回一个包含两个元素的三个列表的列表.

split_list(mylist,3) will return a list of three lists of two elements.

split_list(mylist,4)将返回一个包含两个元素的两个列表和一个元素的两个列表的列表.

split_list(mylist,4) will return a list of two lists of two elements and two lists of one element.

我不在乎哪个元素出现在哪个列表中,只是列表被尽可能均匀地划分了.

I don't care which elements appear in which list, just that the list is divided up as evenly as possible.

推荐答案

numpy.split已经做到了:

numpy.split does this already:

示例:

>>> mylist = np.array([1,2,3,4,5,6])

split_list(mylist,2)将返回一个包含三个元素的两个列表的列表 -[[1,2,3] [4,5,6]].

split_list(mylist,2) will return a list of two lists of three elements - [[1,2,3][4,5,6]].

>>> np.split(mylist, 2)
[array([1, 2, 3]), array([4, 5, 6])]

split_list(mylist,3)将返回三个列表的列表,其中两个 元素.

split_list(mylist,3) will return a list of three lists of two elements.

>>> np.split(mylist, 3)
[array([1, 2]), array([3, 4]), array([5, 6])]

split_list(mylist,4)将返回一个包含两个元素的两个列表的列表 和一个元素的两个列表.

split_list(mylist,4) will return a list of two lists of two elements and two lists of one element.

对于length(mylist)/n的余数不为0的情况,您可能想添加一个异常捕获:

You may probably want to add an exception capture for the cases when the remainder of length(mylist)/n is not 0:

>>> np.split(mylist, 4)
ValueErrorTraceback (most recent call last)
----> 1 np.split(mylist, 4)
...
ValueError: array split does not result in an equal division

这篇关于如何在python中将列表拆分为给定数量的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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