1

我怎样才能得到(以一种非常有效的 python 方式),一组包含在另一个长列表中的子列表??,我用例子解释:

假设我有这个:

List = [[1,2,3],[4,5,6],[7,8,9],[2,4,3],......long list]

我想获得一个将子列表分组的输出,比如说,在一组 7 个子列表中,那么输出将如下所示:

L1 = [1,2,3]
L2 = [4,5,6]
L3 = [7,8,9]
up to L7
then process those 7 lists separately
and then start again....
L1 = [x,x,x] this L1 would be (obviously) the 8th sub-list in the big list "List"
L2 = [x,x,x] this would be the 9th sub-list....and so on

我不知道我是否应该这样称呼它,但这就像制作 7 个子列表的“块”。

是否有可能以快速有效的方式进行?

4

1 回答 1

1

你可以用切片来做到这一点。有关更多详细信息,请参阅解释 Python 的切片表示法

list = [[1,2,3],[4,5,6],[7,8,9],[2,4,3], ... ]

for i in range(0, len(list), 7):
  L1, L2, L3, L4, L5, L6, L7 = list[i:i+7]
  ...

注意:列表的长度必须是 7 的倍数才能执行此操作。如果不是,请附加尽可能多的Nones 以确保它可以被 7 整除。

于 2014-01-03T10:00:49.603 回答