在 Python 中对列表进行分段
我正在寻找一个 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]]
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:
>>> 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]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用列表理解:
You can use list comprehension:
输出不一样,我仍然认为 grouper 函数 很有帮助:
对于 Python2.4和 2.5 没有 izip_longest:
一些演示代码和输出:
输出:
[(0,1,2),(3,4,5),(6,7,8),(9,无,无)]
not the same output, I still think the grouper function is helpful:
for Python2.4 and 2.5 that does not have izip_longest:
some demo code and output:
output:
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
您需要如何使用输出? 如果您只需要迭代它,那么您最好创建一个可迭代的,一个可以产生您的组的迭代:
使用示例:
如果您只循环遍历结果,因为它一次只构造一个子集:
How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups:
Usage example:
This uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time:
对 @omergertel 的修改将允许开发人员实际生成段列表:
A modification to @omergertel will allow the developer to actually generate a list of segments: