我有一个数组,其中包含一组数字的n时间。使用n=2的示例
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]我想要的是这个数组的分区,其中分区的成员
kk=4的示例输出
[[3,0,2,1], [0,1,4,2], [3,4]]k=4的无效输出
[[3,0,2,2], [3,1,4,0], [1,4]](这是一个分区,但分区的第一个元素包含重复项)
实现这一目标的最重要的方式是什么?
发布于 2017-04-12 00:38:15
可以使用collections.Counter和random.sample的组合:
from collections import Counter
import random
def random_partition(seq, k):
cnts = Counter(seq)
# as long as there are enough items to "sample" take a random sample
while len(cnts) >= k:
sample = random.sample(list(cnts), k)
cnts -= Counter(sample)
yield sample
# Fewer different items than the sample size, just return the unique
# items until the Counter is empty
while cnts:
sample = list(cnts)
cnts -= Counter(sample)
yield sample这是一个生成器,yield是示例,所以您可以简单地将它转换为list。
>>> l = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
>>> list(random_partition(l, 4))
[[1, 0, 2, 4], [1, 0, 2, 3], [3, 4]]
>>> list(random_partition(l, 2))
[[1, 0], [3, 0], [1, 4], [2, 3], [4, 2]]
>>> list(random_partition(l, 6))
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
>>> list(random_partition(l, 4))
[[4, 1, 0, 3], [1, 3, 4, 0], [2], [2]]最后一个例子表明,如果函数中的“随机”部分返回“错误”样本,该方法可能会给出奇怪的结果。如果这种情况不应该发生,或者至少不经常发生,那么您需要弄清楚如何对样本进行加权(例如,使用random.choices)来最小化这种可能性。
https://stackoverflow.com/questions/43358302
复制相似问题