在python的标准库或语法技巧中寻找一些东西.
对于非clojure程序员,partition-all应具有以下语义:
partition_all(16, lst) == [lst[0:16], lst[16:32], lst[32:48], lst[48:60]]
假设len(lst)== 60
Python中没有这样的功能.你可以这样做:
from itertools import islice
def chunkwise(n, iterable):
it = iter(iterable)
while True:
chunk = list(islice(it, n))
if not chunk:
break
yield chunk
print list(chunkwise(3, range(10)))
# [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
Run Code Online (Sandbox Code Playgroud)