在日常开发中,有时候需要把一个大列表分割为固定的小列表,再进行相关处理。下面来看看详细的分割方法:
>>> 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]]
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]]
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]]
>>> 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]]
【1】https://blog.csdn.net/weixin_42575593/article/details/83311034