将
len(L)
分解为2和3的块,然后使用循环来分割列表。
import numpy as np
def rand23():
return np.random.randint(2,4)
def get_chunk(sz):
rem = sz
ch = []
while ( rem > 0 ):
if ( rem <= 3 ):
ch.append(rem)
rem = 0
break
elif ( rem == 4 ):
ch.append(2)
ch.append(2)
rem = 0
break
else:
ch.append(rand23())
rem -= ch[-1]
return ch
L = [1,1,1,1,1,1,1,1,1,1,1,1]
ch = get_chunk(len(L))
L2 = []
count = 0
for c in ch:
L2.append(tuple(L[count:count+c]))
count += c
print L2
结果:(每行是迭代的输出)
[(1, 1, 1), (1, 1), (1, 1), (1, 1), (1, 1, 1)]
[(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)]
[(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]
[(1, 1), (1, 1), (1, 1, 1), (1, 1, 1), (1, 1)]
[(1, 1, 1), (1, 1), (1, 1), (1, 1), (1, 1, 1)]
[(1, 1, 1), (1, 1, 1), (1, 1), (1, 1), (1, 1)]
[(1, 1), (1, 1), (1, 1, 1), (1, 1), (1, 1, 1)]
PS:你也可以递归地实现get_chunk()
。
min_chunk=2
和maxchunk=3
运行时,接受的答案在其中一个迭代中为L2给出了[[1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1]]
。 - Vasanth