小编a q*_*a q的帖子

根据项目的长度以块的形式分割python列表

我在这里看到一些关于如何将Python列表拆分成块的好帖子,比如如何在常量大小的块中拆分可迭代的块.大多数帖子涉及分割块或将列表中的所有字符串连接在一起,然后根据正常的片段例程进行限制.

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

我能够在这里制作一些代码:

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 …
Run Code Online (Sandbox Code Playgroud)

python list limit slice chunks

5
推荐指数
1
解决办法
2233
查看次数

标签 统计

chunks ×1

limit ×1

list ×1

python ×1

slice ×1