我正在寻找一个 python 内置函数(或机制)来将列表分割成所需的段长度(不改变输入列表)。这是我已经拥有的代码:
>>> def split_list(list, seg_length):
... inlist = list[:]
... outlist = []
...
... while inlist:
... outlist.append(inlist[0:seg_length])
... inlist[0:seg_length] = []
...
... return outlist
...
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]