Python 如何将列表随机划分为 n 个几乎相等的部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3352737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to randomly partition a list into n nearly equal parts?
提问by Darren J. Fitzpatrick
I have read the answers to the Slicing a list into n nearly-equal-length partitions [duplicate]question.
我已阅读将列表切片为 n 个几乎相等长度的分区 [重复]问题的答案。
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.
我想知道如何修改这些解决方案以将项目随机分配到分区而不是增量分配。
采纳答案by bobince
Call random.shuffle()on the list before partitioning it.
random.shuffle()在分区之前调用列表。
回答by SilentGhost
shuffle input list.
随机输入列表。
回答by Teodor Pripoae
First you randomize the list and then you split it in n nearly equal parts.
首先将列表随机化,然后将其分成 n 个几乎相等的部分。
回答by ErichBSchulz
Complete 2018 solution (python 3.6):
完整的 2018 解决方案(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
谨防!这可能会改变您的原始列表

