问题
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