有几种方法:
您可以使用嵌套列表理解,将索引放入列表中:
(不过,索引的广泛使用是非常不和谐的)
theList = list(range(10))
N = 3
L = len(theList)
subList = [ [theList[j] for j in range(i,min(i+N,L))] for i in range(0,L,N) ]
print(subList)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
你也可以用itertools来做。groupby使用迭代器作为分组键或itertools。每个子范围的islice(,N):
from itertools import groupby
group = iter(range(len(theList)))
subList = [ list(g) for _,g in groupby(theList,key=lambda _:next(group)//N) ]
print(subList)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
from itertools import islice
iList = iter(theList)
subList = [ list(islice(iList,N)) for _ in range(0,len(theList),N) ]
print(subList)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
如果不能使用库,可以使用zip()获取列表中的迭代器块:
iList = iter(theList)
subList = [[n for _,n in zip(range(N),iList)] for _ in range(0,len(theList),N)]
print(subList)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
或者使用next()函数进行映射:
iList = iter(theList)
subList = [ [f, *map(next,[iList]*(N-1))] for f in iList ]
print(subList)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
当然,总有好的for循环方法:
subList = [[]]
for n in theList:
L,V = (subList[-1],n) if len(subList[-1])<N else (subList,[n])
L.append(V)
print(subList)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]