Python - randomly splits a list into n almost equal parts

I read the answers in Python: slicing a list into n questions of almost equal length .

This is the accepted answer :

def partition(lst, n): 
    division = len(lst) / float(n) 
    return [ lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n) ]

I am wondering how these solutions can be modified to randomly assign elements to a section rather than incremental assignment.

Thanks, S :-)

+9
source share
4 answers

Call random.shuffle()in the list before splitting it.

+22
source

Complete the 2018 solution (Python 3.6):

import random 
def partition (list_in, n):
    random.shuffle(list_in)
    return [list_in[i::n] for i in range(n)]

Caution! this may change your initial list

+6
source

.

+1

First you produce a list, and then divide it into n almost equal parts.

0
source

All Articles