The most pythonic way to slice a Python list every 100 elements [duplicate]

浪子不回头ぞ 提交于 2019-12-06 10:52:44

问题


I have a list contains many elements. I want to slice it every 100 elements to a list of several lists.

For example:

>>> a = range(256)
>>> b = slice(a, 100)

b should then be [[0,1,2,...99],[100,101,102,...199],[200,201,...,255]].

What's the most pythonic and elegent way to do that?


回答1:


This should do the trick:

[a[i:i+100] for i in range(0, len(a), 100)]

range takes an optional third step argument, so range(0, n, 100) will be 0, 100, 200, ....



来源:https://stackoverflow.com/questions/27538981/the-most-pythonic-way-to-slice-a-python-list-every-100-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!