How to split a list into a given number of subscriptions in python

Possible duplicates:
splitting a list of arbitrary size only into approximately equal N-equal parts
How do you split a list into pieces of uniform size in Python?

I need to create a function that splits a list into a list of lists, each of which contains an equal number of elements (or as many as possible).

eg.

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,3) will return a list of three lists of two elements.

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

I don’t care what elements appear in the list, just so that the list is divided as evenly as possible.

+4
source share

Source: https://habr.com/ru/post/1300851/


All Articles