The most pythonic way to slice a Python list every

2019-04-13 09:23发布

问题:

This question already has an answer here:

  • Slice a binary number into groups of five digits 7 answers

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, ....



标签: python slice