Python - randomly partition a list into n nearly e

2019-04-07 09:38发布

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 :-)

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-07 09:58

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

查看更多
一纸荒年 Trace。
3楼-- · 2019-04-07 10:04

shuffle input list.

查看更多
放荡不羁爱自由
4楼-- · 2019-04-07 10:08

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

查看更多
萌系小妹纸
5楼-- · 2019-04-07 10:21

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

查看更多
登录 后发表回答