1 分割大列表为1个元素的小列表
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
r = [[x] for x in a]
r
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
2 分割大列表为3个元素的小列表
In [17]: lst
Out[18]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [18]: for i in range(0,len(lst),3): print(lst[i:i+3])
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
In [35]: lst
Out[35]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [36]: b = [lst[i:i+3] for i in range(0,len(lst),3)]
In [37]: b
Out[37]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
lambda方法
In [10]: f = lambda a:map(lambda b:a[b:b+3],range(0,len(a),3))
In [11]: lst
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [12]: f(lst)
Out[12]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
平均n等份
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l = len(a) # a 的长度
l
10
n = 5 # 平均 5 等份
step = int(l/n) # 步长
step
2
b = [a[i:i+step] for i in range(0, l, step)]
b
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]