有人提出了一个相关的问题:
Slicing a list into a list of sub-lists
例如,如果您的源列表是:
the_list = [1,2,3,4,5,6,7,8,9,... ]
你可以拆分它像:
split_list = [the_list[i:i+n] for i in range(0,len(the_list),n)]
假设n是您的子列表长度,结果将是:
[[1,...,n],[n+1,n+2,n+3,2n],...]
然后你可以像下面这样迭代它:
for sub_list in split_list:
# Do something to the sub_list
字符串也是如此.
这是一个实际的例子:
>>> n = 2
>>> listo = [1,9]
>>> split_list = [listo[i:i+n] for i in range(0,len(listo),n)]
>>> split_list
[[1,2],[3,4],[5,6],[7,8],[9]]
>>> listo = '123456789'
>>> split_list = [listo[i:i+n] for i in range(0,n)]
>>> split_list
['12','34','56','78','9']
如果觉得《python生成指定长度的列表_python – 如何将列表或字符串解析为固定长度的块》对你有帮助,请点赞、收藏,并留下你的观点哦!