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

python: Splitting a list into n sublists by index

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

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

例如,给定以下列表:

l = [1,1,1,2,2,2,3,3,3]
n = 3

在这种情况下,我需要将列表拆分为 3 个列表,输出如下:

[[1,2,3],[1,2,3],[1,2,3]]

我可以让 n for 循环跳过每个 nth 步骤,但我确信有更好的方法。

使用 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)])])

输出:

[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

注意:如果分块不均匀也可以用from itertools import izip_longest

关于您描述的循环方法,请参见How do you split a list into evenly sized chunks?

A better way 将使用第 3 方库,例如 numpy。这利用了矢量化计算:

示例 #1

import numpy as np

l = np.array([1,1,1,2,2,2,3,3,3])
n = 3

res = l.reshape((len(l)/n), n).T

print(res)

array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

示例 #2

import numpy as np

l = np.array([1,2,3,4,5,6,7,8])
n = 4

res = l.reshape((len(l)/n, n)).T

print(res)

array([[1, 5],
       [2, 6],
       [3, 7],
       [4, 8]])

我找到了另一个答案,非常简单,使用模数:

l = [1,2,3,4,5,6,7,8]
n = 4
for i in range (n):
    a.append([])
for i in range(len(l)):
    a[i%n].append(l[i])

输出:

[[1, 5], [2, 6], [3, 7], [4, 8]]