Reputation: 1188
I have a list containing sublists elements that look like this:
li = [[1],[2,3,4],[5,6],[7,8,9,10],[11],[12],[13],[14,15,16]]
I would like to concatenate all the sublists that are shorter than a certain value limit
with the next sublists until the length of the new sublist is >= limit
Examples:
if limit=3
the previous list should became:
li_result = [[1,2,3,4], [5,6,7,8,9,10], [11,12,13], [14,15,16]]
if limit=2
the previous list should became:
li_result = [[1,2,3,4], [5,6] [7,8,9,10], [11,12], [13,14,15,16]]
if limit=1
the previous list should became:
li_result = [[1],[2,3,4],[5,6],[7,8,9,10],[11],[12],[13],[14,15,16]]
To concatenate I could use from
itertools import chain
list(chain.from_iterable(li)
How would I limit the concatenation based on my limit
value?
Upvotes: 1
Views: 333
Reputation: 17794
You can use the function accumulate()
:
def func(l, limit):
acc = list(accumulate(l, lambda x, y: x + y if len(x) < limit else y))
res = list(filter(lambda x: len(x) >= limit, acc))
if len(acc[-1]) < limit:
res.append(acc[-1])
return res
Test:
l = [[1],[2,3,4],[5,6],[7,8,9,10],[11],[12],[13],[14,15,16]]
print(func(l, 3))
# [[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13], [14, 15, 16]]
print(func(l, 2))
# [[1, 2, 3, 4], [5, 6], [7, 8, 9, 10], [11, 12], [13, 14, 15, 16]]
print(func(l, 1))
# [[1], [2, 3, 4], [5, 6], [7, 8, 9, 10], [11], [12], [13], [14, 15, 16]]
l = [[1,2,3],[4]]
print(func(l, 3))
# [[1, 2, 3], [4]]
l = [[1],[2]]
print(func(l, 3))
# [[1, 2]]
Upvotes: 0
Reputation: 6581
This one might work:
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
Few tests:
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]]
This solution contains typing annotations. To use in Python 2.7, replace
def combine_to_max_size(l: List[List[Any]], limit: int) -> List[List[Any]]:
With:
def combine_to_max_size(l, limit):
# type: (List[List[Any]], int) -> List[List[Any]]
Upvotes: 2
Reputation: 24232
I would simply go with a loop:
def limited_concat(li, limit):
if not li:
return []
out = [[]]
for sublist in li:
if len(out[-1]) < limit:
out[-1].extend(sublist)
else:
out.append(sublist[:])
return out
li = [[1],[2,3,4],[5,6],[7,8,9,10],[11],[12],[13],[14,15,16]]
limited_concat(li, 2)
# [[1, 2, 3, 4], [5, 6], [7, 8, 9, 10], [11, 12], [13, 14, 15, 16]]
Upvotes: 2