li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] #arr是被分割的list,n是每个chunk中含n元素。 def chunks(arr, n): return [arr[i:i+n] for i in range(0, len(arr), n)] m = chunks(li,4) print m
结果:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18]]
#或者让一共有m块,自动分(尽可能平均) #split the arr into N chunks def chunks(arr, m): n = int(math.ceil(len(arr) / float(m))) return [arr[i:i + n] for i in range(0, len(arr), n)] m = chunks(li,4) print m
结果:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18]]
时间: 2024-10-27 00:51:36