将 python 列表拆分为其他“子列表";即较小的列表 [英] Split a python list into other "sublists" i.e smaller lists

查看:52
本文介绍了将 python 列表拆分为其他“子列表";即较小的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长达 1000 个的 python 列表.类似的东西:

I have a python list which runs into 1000's. Something like:

data=["I","am","a","python","programmer".....]

其中,len(data)= 说 1003

where, len(data)= say 1003

我现在想通过将原始列表分成 100 个块来创建此列表(数据)的子集.所以,最后,我想要像这样:

I would now like to create a subset of this list (data) by splitting the orginal list into chunks of 100. So, at the end, Id like to have something like:

data_chunk1=[.....] #first 100 items of list data
data_chunk2=[.....] #second 100 items of list data
.
.
.
data_chunk11=[.....] # remainder of the entries,& its len <=100, len(data_chunk_11)=3

有没有pythonic的方法来完成这个任务?显然我可以使用 data[0:100] 等等,但我假设这非常非 Pythonic 并且非常低效.

Is there a pythonic way to achieve this task? Obviously I can use data[0:100] and so on, but I am assuming that is terribly non-pythonic and very inefficient.

非常感谢.

推荐答案

我想说

chunks = [data[x:x+100] for x in range(0, len(data), 100)]

如果你使用的是 python 2.x 而不是 3.x,你可以通过使用 xrange() 来提高内存效率,将上面的代码改为:

If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange(), changing the above code to:

chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]

这篇关于将 python 列表拆分为其他“子列表";即较小的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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