Python - randomly partition a list into n nearly e

2019-04-07 09:42发布

问题:

I have read the answers to the Python: Slicing a list into n nearly-equal-length partitions question.

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 does one modify these solutions in order to randomly assign items to a partition as opposed to incremental assignment.

Thanks, S :-)

回答1:

Call random.shuffle() on the list before partitioning it.



回答2:

Complete 2018 solution (pytyon 3.6):

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

Beware! this may mutate your original list



回答3:

shuffle input list.



回答4:

First you randomize the list and then you split it in n nearly equal parts.