我怎样才能(以一种非常有效的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 个子列表的“ block ”。
是否可以快速有效地实现?
最佳答案
你可以通过切片来做到这一点。请参阅Explain Python's slice notation了解更多详情。
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 的倍数才能执行此操作。如果不是,请附加尽可能多的 None
以确保它能被 7 整除。
关于python - 返回列表中包含的子列表,固定大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20900776/