python - 返回列表中包含的子列表,固定大小

标签 python list split sublist chunking

我怎样才能(以一种非常有效的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/

相关文章:

Python - 无效模式 ('w' ) 或文件名

python - GPU 上的训练速度会随着时间变慢

python - 如何检查列表中是否出现两个列表项的任意组合

java - 使用 split() 数组索引越界后但在循环中读取数组

C# 写入多个文件而无需不断关闭/重新打开流。流作家?

python - IronPython与WPF编译exe pyc错误

python - 在 python 中解压缩,交互式与脚本调用

tsql - T-SQL : Parsing String with Multiple delimiters

java - 检查列表是否正确

c - 将 void* 指针转换为 char* 指针并对其进行指针算术运算是否有效?