python - 如何在每第 n 个项目之后创建列表列表

标签 python

在 python 中,如何在每 5 个项目之后创建一个列表列表?

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

预期输出:

new_list = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j']....]

最佳答案

new_list = [my_list[i:i + 5] for i in xrange(0, len(my_list), 5)]

这里发生的是从 0 - 5、5 - 10 等获取数据 block 来创建子列表

关于python - 如何在每第 n 个项目之后创建列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059938/

相关文章:

python - Tensorflow - 在 tensorflow.models.embeddings 中没有名为 'embeddings' 的模块

javascript - 我的自动建议无法正常工作?

python - 如何优化三对角矩阵的特征值/向量计算

python - 尽管我可以看到它已创建,但为什么我得到 "table not found"?

python - 如何使用 python 运行多个可执行文件?

Python "with"语句语法

python - 替换所有连续重复的字母忽略特定单词

python - 阅读这个斐波那契函数

python - 在 Python Bottle 中使用异步 POST 请求?

python - 没有名为 traitlets.config.application 的模块