Python:连接列表的所有连续子列表,直到满足条件

标签 python python-2.7 list

我有一个包含子列表元素的列表,如下所示:

li = [[1],[2,3,4],[5,6],[7,8,9,10],[11],[12],[13],[14,15,16]]

我想将所有小于特定值 limit 的子列表与下一个子列表连接起来,直到新子列表的长度 >= limit

例子:

如果 limit=3 之前的列表应该变成:

li_result = [[1,2,3,4], [5,6,7,8,9,10], [11,12,13], [14,15,16]]  

如果 limit=2 之前的列表应该变成:

li_result = [[1,2,3,4], [5,6] [7,8,9,10], [11,12], [13,14,15,16]]  

如果 limit=1 之前的列表应该变成:

li_result = [[1],[2,3,4],[5,6],[7,8,9,10],[11],[12],[13],[14,15,16]]

为了连接我可以使用 from

 itertools import chain
 list(chain.from_iterable(li)

我如何根据我的 limit 值限制连接?

最佳答案

这个可能有用:

from typing import Any, List

def combine_to_max_size(l: List[List[Any]], limit: int) -> List[List[Any]]:
    origin = l[:]  # Don't change the original l
    result = [[]]
    while origin:
        if len(result[-1]) >= limit:
            result.append([])
        result[-1].extend(origin.pop(0))
    return result

几个测试:

l = [[1],[2, 3],[4, 5, 6]]
assert combine_to_max_size(l, 1) == [[1], [2, 3], [4, 5, 6]]
assert combine_to_max_size(l, 2) == [[1, 2, 3], [4, 5, 6]]
assert combine_to_max_size(l, 4) == [[1, 2, 3, 4, 5, 6]]
assert l == [[1],[2, 3],[4, 5, 6]]

此解决方案包含键入注释。要在 Python 2.7 中使用,请替换

def combine_to_max_size(l: List[List[Any]], limit: int) -> List[List[Any]]:

与:

def combine_to_max_size(l, limit):
    # type: (List[List[Any]], int) -> List[List[Any]]

关于Python:连接列表的所有连续子列表,直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55019827/

相关文章:

python - matplotlib 图缩放 : ticklabels don't get updated (Python)

python - 使用python从mysql查询列表中提取ip地址

python - 日期时间 'has no attribute now'

python - 如何用 Numpy 和 Matplotlib 散点图绘制两个同心圆

python - 获取 CIDR 格式的下一个子网

python - 名称错误 : name 'PROTOCOL_TLS' is not defined

C# - 如何在列表中添加所有 system.drawing.color 项目?

java - java中字符串数组数组的数据结构

python - 将文本框边缘与图像角对齐

python - 如何grep一些字符串(IP :port) from text file and print in screen using Python?