如何将列表拆分为N个随机但最小的块

时间:2013-01-20 18:06:22

标签: python

例如:我想在range(37)个块中拆分n=5,每个块都有 len(chunk) >= 4

3 个答案:

答案 0 :(得分:3)

>>> def divide(lst, min_size, split_size):
    it = iter(lst)
    from itertools import islice
    size = len(lst)
    for i in range(split_size - 1,0,-1):
        s = random.randint(min_size, size -  min_size * i)
        yield list(islice(it,0,s))
        size -= s
    yield list(it)


>>> list(divide(range(37), 4, 5))
[[0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22], [23, 24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35, 36]]
>>> list(divide(range(37), 4, 5))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22], [23, 24, 25, 26], [27, 28, 29, 30, 31], [32, 33, 34, 35, 36]]
>>> list(divide(range(37), 4, 5))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36]]
>>> list(divide(range(37), 4, 5))
[[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31], [32, 33, 34, 35, 36]]
>>> 

答案 1 :(得分:1)

例如,您可以首先将n个块的大小设置为4,然后计算:r =(m = 37 mod n),如果m> = 20。然后只需将1添加到第一个块并减少r,将1减少到第二个块并减少r ....然后重复直到r = 0.然后你有你的块并且你可以填充它们。

答案 2 :(得分:1)

 def divide(val, num=5, minSize=4):
     ''' Divides val into # num chunks with each being at least of size minSize.
         It limits max size of a chunk using math.ceil(val/(num-len(chunks)))'''
     import random
     import math
     chunks = []
     for i in xrange(num-1):
         maxSize = math.ceil(val/(num-len(chunks)))
         newSize = random.randint(minSize, maxSize)
         val = val - newSize
         chunks.append(newSize)
     chunks.append(val)
     return chunks

使用不同的参数调用divide

>>> divide(37,5,4)
>>> [7, 5, 4, 10, 11]
>>> divide(37,5,4)
>>> [4, 5, 4, 10, 14]
>>> divide(50,6,5)
>>> [6, 8, 8, 5, 9, 14]