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

时间:2013-02-04 03:04:38

标签: python list limit chunks slice

我在这里看到一些关于如何将Python列表分成像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] ]] (每个数字引用字符串列表中的项目)

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

我知道代码非常糟糕,我应该使用生成器。我只是不确定如何做到这一点。

感谢。

2 个答案:

答案 0 :(得分:3)

这样的事情应该有效

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模块

答案 1 :(得分:1)

这只是一个班轮。希望它有用

>>>list=[[1,2], [1]]
>>>sorted(list, key=lambda sublist: len(sublist))
[[1], [1,2]]

此外:

>>>list=[[1,2,3],[1],[1,2]]
>>>sorted(list, key=lambda sublist: -len(sublist))
[[1,2,3], [1,2], [1]]