如何将任意长度的列表拆分为大小相等的 block ?
参见 How to iterate over a list in chunks if数据结果直接循环使用,不需要存储。
对于带有字符串输入的相同问题,请参阅 Split string every nth character? .尽管存在一些差异,但通常适用相同的技术。
请您参考如下方法:
这是一个生成大小均匀的 block 的生成器:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[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]]
对于 Python 2,使用 xrange 而不是 range:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), n):
yield lst[i:i + n]
下面是列表理解单行。不过,上面的方法更可取,因为使用命名函数可以使代码更容易理解。对于 Python 3:
[lst[i:i + n] for i in range(0, len(lst), n)]
对于 Python 2:
[lst[i:i + n] for i in xrange(0, len(lst), n)]
