另一个简单可读的chunker的尝试。
def chunk(iterable, count): # returns a *generator* that divides `iterable` into `count` of contiguous chunks of similar size
assert count >= 1
return (iterable[int(_*len(iterable)/count+0.5):int((_+1)*len(iterable)/count+0.5)] for _ in range(count))
print("Chunk count: ", len(list( chunk(range(105),10))))
print("Chunks: ", list( chunk(range(105),10)))
print("Chunks: ", list(map(list,chunk(range(105),10))))
print("Chunk lengths:", list(map(len, chunk(range(105),10))))
print("Testing...")
for iterable_length in range(100):
for chunk_count in range(1,100):
chunks = list(chunk(range(iterable_length),chunk_count))
assert chunk_count == len(chunks)
assert iterable_length == sum(map(len,chunks))
assert all(map(lambda _:abs(len(_)-iterable_length/chunk_count)<=1,chunks))
print("Okay")
输出:
Chunk count: 10
Chunks: [range(0, 11), range(11, 21), range(21, 32), range(32, 42), range(42, 53), range(53, 63), range(63, 74), range(74, 84), range(84, 95), range(95, 105)]
Chunks: [[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, 37, 38, 39, 40, 41], [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52], [53, 54, 55, 56, 57, 58, 59, 60, 61, 62], [63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73], [74, 75, 76, 77, 78, 79, 80, 81, 82, 83], [84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94], [95, 96, 97, 98, 99, 100, 101, 102, 103, 104]]
Chunk lengths: [11, 10, 11, 10, 11, 10, 11, 10, 11, 10]
Testing...
Okay