且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

返回较大列表中每N个项目的列表的Python方式

更新时间:2022-05-07 22:50:18

您可以使用列表理解以Python方式进行此操作.见下文:

You can use list comprehension to do this in a Pythonic manner. See below:

def group(original_list,n=50):

    return [original_list[x:x+n] for x in xrange(0,len(original_list),n)]

您实际上根本不需要任何功能,但是想通了,我会展示这种功能方式,以防您想要更改每个子列表中的项目数.效果也一样:

You actually don't need a function for this at all, but figured I'd show the functional way in case you wanted to vary the number of items in each sublist. This works just as well:

[original_list[x:x+50] for x in xrange(0,len(original_list),50)]