How to randomly partition a list into n nearly equal parts?

后端 未结 4 1154
耶瑟儿~
耶瑟儿~ 2020-12-10 02:46

I have read the answers to the Slicing a list into n nearly-equal-length partitions [duplicate] question.

This is the accepted answer:

def partition(         


        
相关标签:
4条回答
  • 2020-12-10 03:39

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

    0 讨论(0)
  • 2020-12-10 03:42

    shuffle input list.

    0 讨论(0)
  • 2020-12-10 03:50

    Complete 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)]
    

    Beware! this may mutate your original list

    0 讨论(0)
  • 2020-12-10 03:51

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

    0 讨论(0)
提交回复
热议问题