python 如何在python中将列表拆分为给定数量的子列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2235526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:08:10  来源:igfitidea点击:

How to split a list into a given number of sub-lists in python

pythonlist

提问by Richard

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?

可能的重复项:
将任意大小的列表拆分为大致 N 相等的部分
如何在 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).

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

e.g.

例如

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


mylist = [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,2)将返回一个包含三个元素的两个列表的列表 - [[1,2,3][4,5,6]]

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

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

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

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

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

我不在乎哪些元素出现在哪个列表中,只关心列表尽可能均匀地划分。

回答by dalloliogm

numpy.split does this already:

numpy.split 已经这样做了:

Examples:

例子:

>>> mylist = np.array([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,2) 将返回包含三个元素的两个列表的列表 - [[1,2,3][4,5,6]]。

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

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

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

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

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

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

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

您可能希望为 length(mylist)/n 的余数不为 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