python - 在python中按一定长度将列表列表组合到另一个列表列表

标签 python

我正在寻找一个可以转换的衬垫

[[1], [1, 1], [1, 1, 1], [1], [1], [1], [1, 1, 1, 1]]

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1, 1]]

算法将列表组合到某个阈值长度。

我现在有这个

batched = []
batch = []
for l in lists:
    batch.extend(l)
    if len(batch) > threshold:
        batched.append(batch)
        batch = []

最佳答案

您的原始实现没有任何问题,但如果您坚持使用 oneliner,那么这里有一个丑陋的选择:

from itertools import accumulate, chain, groupby

THRESHOLD = 3
l = [[1], [1, 1], [1, 1, 1], [1], [1], [1], [1, 1, 1, 1]]
res = [[y for x in g for y in x[1]]
       for k, g in groupby(zip(chain([0], accumulate(len(x) for x in l)), l),
                           lambda x: x[0] // THRESHOLD)]
print(res)

输出:

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1, 1]]

想法是生成 (item count so far, sublist) 元组的列表,并通过将计数除以 THRESHOLD 来对它们进行分组。

>>> temp = list(zip(chain([0], accumulate(len(x) for x in l)), l))
>>> temp
[(0, [1]), (1, [1, 1]), (3, [1, 1, 1]), (6, [1]), (7, [1]), (8, [1]), (9, [1, 1, 1, 1])]
>>> groups = [list(g) for k, g in groupby(temp, lambda x: x[0] // THRESHOLD)]
>>> groups
[[(0, [1]), (1, [1, 1])], [(3, [1, 1, 1])], [(6, [1]), (7, [1]), (8, [1])], [(9, [1, 1, 1, 1])]]
>>> [[y for x in g for y in x[1]] for g in groups]
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1, 1]]

关于python - 在python中按一定长度将列表列表组合到另一个列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42093313/

相关文章:

python - 使用 2x2 矩阵广播 2D 点列表的点积

python - 在多线程环境中将 JSON 转储到文件

Python 开源密码学工具包

python - 将 DataFrame 格式化为面向行的 JSON 对象(电子表格样式数据透视表)

python - 将 Teradata SQL 结果打印到命令行 - Python

python - 编写不使用 100% CPU 的 tail -f python 脚本

python - 如何在 python-docx 中获取单元格背景颜色?

python - 将包含字典的 Pandas 列转换为多行

Python 括号约定

python - SQLALCHEMY 忽略查询中的重音