python - 根据项目的长度将 python 列表拆分成 block

标签 python list limit chunks slice

我在这里看到一些关于如何将 Python 列表拆分成 block 的很棒的帖子,例如 how to split an iterable in constant-size chunks . 大多数帖子都涉及划分块或将列表中的所有字符串连接在一起,然后根据正常的切片例程进行限制。

但是,我需要根据字符限制执行类似的操作。如果您有一个句子列表,但不能截断列表中的任何切片。

我能够在这里生成一些代码:

def _splicegen(maxchars, stringlist):
    """
    Return a list of slices to print based on maxchars string-length boundary.
    """
    count = 0  # start at 0
    slices = []  # master list to append slices to.
    tmpslices = []  # tmp list where we append slice numbers.

    for i, each in enumerate(stringlist):
        itemlength = len(each)
        runningcount = count + itemlength
        if runningcount < int(maxchars):
            count = runningcount
            tmpslices.append(i)
        elif runningcount > int(maxchars):
            slices.append(tmpslices)
            tmpslices = []
            count = 0 + itemlength
            tmpslices.append(i)
        if i==len(stringlist)-1:
            slices.append(tmpslices)
    return slices

输出应该返回如下内容: 切片是:[[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20 ]] (每个数字引用 stringlist 中的一个项目)

所以,当我遍历这个列表列表时,我可以使用类似“”.join([item for item in each]) 的东西在一行上打印 0,1,2,3,4,5,6 , 7,8,9,10,11,12,13 在另一个上。有时,一个列表可能只有 2 个项目,因为这两个项目中的每一个都非常长(加起来不超过 380 个字符或其他任何字符的限制)。

我知道代码很糟糕,我应该使用生成器。我只是不确定该怎么做。

谢谢。

最佳答案

像这样的东西应该可以工作

def _splicegen(maxchars, stringlist):
    """
    Return a list of slices to print based on maxchars string-length boundary.
    """
    runningcount = 0  # start at 0
    tmpslice = []  # tmp list where we append slice numbers.
    for i, item in enumerate(stringlist):
        runningcount += len(item)
        if runningcount <= int(maxchars):
            tmpslice.append(i)
        else:
            yield tmpslice
            tmpslice = [i]
            runningcount = len(item)
    yield(tmpslice)

另见 textwrap模块

关于python - 根据项目的长度将 python 列表拆分成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14679836/

相关文章:

python - 在此MapReduce问题中,如何选择有选择的值之和大于3?

python - Postgres 函数作为 SQLAlchemy 中的列

python - 图遍历,也许是另一种数学?

python - 测试 Django throttle

python - 如何从 Python 列表中删除引号?

python - 在列表中查找形成循环引用的 3 对集合

java - 如何在 Java 中设置线程限制

php - MYSQL PHP 的 order by 和 limit 1 返回 null

java - 创建类对象列表以将它们与另一个类对象进行比较

filter - XQuery - 仅检索部分信息