python:按索引将列表拆分为n个子列表

Ort*_*man 2 python split list sublist

我希望这个问题不是重复的;我找到了类似的,但不完全是我需要的。

我想要一种将列表拆分为n个子列表的有效方法,其中每个索引转到不同的列表,直到我们到达第n 个索引,然后接下来的n 个索引以相同的顺序转到我们已有的列表,依此类推。 .

例如,给定以下列表:

l = [1,1,1,2,2,2,3,3,3]
n = 3
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我需要将列表拆分为具有所需输出的 ​​3 个列表:

[[1,2,3],[1,2,3],[1,2,3]]
Run Code Online (Sandbox Code Playgroud)

我可以创建n 个for 循环,每n步跳过一次,但我确信有更好的方法。

Rak*_*esh 7

使用zip和列表理解

l = [1,1,1,2,2,2,3,3,3]
n = 3
print([list(i) for i in zip(*[l[i:i+n] for i in range(0, len(l), n)])])
Run Code Online (Sandbox Code Playgroud)

输出:

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

注意:from itertools import izip_longest如果块不均匀,您也可以使用。