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 :-)
Call random.shuffle()in the list before splitting it.
random.shuffle()
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
.
First you produce a list, and then divide it into n almost equal parts.