Home>

### python : Split the list into n elements

Let's say there is a list`l`and the number```j < = len (l) /2```how to split the list l into j subarrays so that the lengths of the longest and shortest subarrays differ by no more than 1.

Are you familiar with the concept of integer division?

MBo2021-11-25 06:48:12

Bresenham's algorithm.

Stanislav Volodarskiy2021-11-25 06:48:12

The restriction on j need not be imposed. The problem is solvable for any natural j.

Stanislav Volodarskiy2021-11-25 06:48:12

I would implement a generator

``````def generate_sublists (source, sublist_length):
for i in range (0, len (source), sublist_length):
yield source [i: i + sublist_length]
``````

it is not entirely clear how in this code it is possible to fulfill the task condition so that the length of the longest and shortest subarrays differs by no more than 1

SergFSM2021-11-25 06:48:12

@SergFSM yeah. It's always fun when the questioner accepts an answer that doesn't do what is required.

Эникейщик2021-11-25 06:48:12

I would implement a generator

``````def generate_sublists (source, sublist_length):
for i in range (0, len (source), sublist_length):
yield source [i: i + sublist_length]
``````

it is not entirely clear how in this code it is possible to fulfill the task condition so that the length of the longest and shortest subarrays differs by no more than 1

SergFSM2021-11-25 06:48:12

@SergFSM yeah. It's always fun when the questioner accepts an answer that doesn't do what is required.

Эникейщик2021-11-25 06:48:12

I managed to split the list with the following code:

``````j= 5
l= [1,2,3,4,5,6,7,8,9,10,11,12,13]
res= []
l1, l2= divmod (len (l), j)
r= [l1 + 1] * l2 + [l1] * (j-l2) # the length of the resulting lists
temp= l.copy ()
for i in r:
res.append (temp [: i])
del temp [: i]
print (res) # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11], [12, 13]]
``````

total, we got the given five lists, the length of the longest-3, the shortest-2

Your result is correct. You need to get rid of the del operation -it slows everything down.

Stanislav Volodarskiy2021-11-25 06:48:12

@StanislavVolodarskiy, I agree, this code can be improved

SergFSM2021-11-25 06:48:12

I managed to split the list with the following code:

``````j= 5
l= [1,2,3,4,5,6,7,8,9,10,11,12,13]
res= []
l1, l2= divmod (len (l), j)
r= [l1 + 1] * l2 + [l1] * (j-l2) # the length of the resulting lists
temp= l.copy ()
for i in r:
res.append (temp [: i])
del temp [: i]
print (res) # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11], [12, 13]]
``````

total, we got the given five lists, the length of the longest-3, the shortest-2

Your result is correct. You need to get rid of the del operation -it slows everything down.

Stanislav Volodarskiy2021-11-25 06:48:12

@StanislavVolodarskiy, I agree, this code can be improved

SergFSM2021-11-25 06:48:12