返回较大列表中每N个项目的列表的Python方式 [英] Pythonic way to return lists of every N items in a larger list

查看:65
本文介绍了返回较大列表中每N个项目的列表的Python方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约250个元素的较大列表.我需要将每50个元素分组到一个子列表中,并遍历每个子列表.

I have a larger list of approximately 250 elements. I need to group every 50 elements into a sub-list and iterate through each of the sub-lists.

例如:

largerList = [0, 1, ... ..., 268]

我希望子列表看起来像:

I want the sub lists to look like:

subLists = [[0, 1, ... ..., 49], [50, 51, ... ..., 99], ... ..., [250, 251, ... ..., 268]]

然后,我将能够迭代子列表并为它们中的每一个做一些事情.

Then I will be able to iterate the sub lists and do something for each of them.

for ls in subLists:
  for i in ls:
    DO SOMETHING...

推荐答案

您可以使用列表理解以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)]

这篇关于返回较大列表中每N个项目的列表的Python方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆