我有一个包含子列表元素的列表,如下所示:
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/